黑马程序员技术交流社区
标题:
求解!请大家帮忙看看!
[打印本页]
作者:
莫若吻
时间:
2014-4-23 23:09
标题:
求解!请大家帮忙看看!
本帖最后由 莫若吻 于 2014-4-26 09:27 编辑
练习题:定义一个类MathDemo,类的内部重载round方法,分别实现对单精度,双精度类型数据进行四舍五入的功能,要处理的实型数据作为参数,方法体最后将得到的结果返回
在main方法中定义float与double类型变量,分别赋初值,创建mathDemo类的对象,调用round()方法,将结果显示在屏幕上。
下面的代码是我自己整理的。有些太过繁琐了,不知道谁有更简单的方法。最好可以将四舍五入的方法过程显示出来,而不是直接调用系统的……
class MathDemo{
public static int round(float x){
int y=(int)x;
float a=x-y; //a为整数的小数部分
if(x>=0)
{
if(a>0.5)
return y+1;
else
return y;
}else
{
if(a>0.5)
return y-1;
else
return y;
}
}
public static int round(double x){
int y=(int)x;
double a=x-y;//a为整数的小数部分
if(x>=0)
{
if(a>0.5)
return y+1;
else
return y;
}else
{
if(a>0.5)
return y-1;
else
return y;
}
}
}
class Test15{
public static void main(String[] args){
float f=2.3f;
double d=19.7;
MathDemo arrays=new MathDemo();
//arrays.round(f);
//arrays.round(d);
System.out.println(f+"四舍五入后的值为"+arrays.round(f));
System.out.println(d+"四舍五入后的值为"+arrays.round(d));
}
}
作者:
龙健
时间:
2014-4-24 19:12
package cn.itheima.luntan;
public class MathDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MathDemo md=new MathDemo();
float num1=12.445f;
double num2=12.54;
float num3=md.round(num1);
double num4=md.round(num2);
System.out.println(num3);
System.out.println(num4);
}
private float round(float num1) {
// TODO Auto-generated method stub
return (Math.round(num1));
}
private double round(double num2){
return (Math.round(num2));
}
}
作者:
龙健
时间:
2014-4-25 16:45
龙健 发表于 2014-4-24 19:12
package cn.itheima.luntan;
public class MathDemo {
四舍五入的方法是Math类自带的,建议你还是去看看视频吧。。。。
作者:
eternallove
时间:
2014-4-25 18:11
实际上学习写一些API方法时,可以去参考以下API源代码。round()方法可以到Math类里看看源码。
作者:
你为谁归来
时间:
2014-4-25 18:25
使用三元运算符,代码上面看起来会比较简洁干净点!
作者:
小流氓123
时间:
2014-4-25 19:54
你去查看下math这个类 有四舍五入 的方法!!
作者:
pray
时间:
2014-4-26 00:31
我是来收集资料滴...
作者:
和静清寂
时间:
2014-4-26 02:41
我是来看看会不会的。 基础很重要!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2