public class round {
public static void main(String[] args) {
double n = 1.7;
int result;
result = round(n);
System.out.println(result);
}

public static int round(double num) {
double n;
n = num - (int)num;
if ((int)(n*10) >= 5)
return (int)num+1;
else
return (int)num;
}
}
这段代码有什么问题么?

解决方案 »

  1.   

    要四舍五入 使用java自带的方法吧 肯定没问题
    result = Math.round(n)
      

  2.   

    方法名能用类名?
    那个必须是构造函数吧
    一般类名都大写: public class Round
      

  3.   

    这段代码没问题,但是有几个编程风格不太好,①类名要大写,②把main()方法最好写在round()下面,③round的方法最好写成非static方法,就是public int round(double num){},再在main()方法里result = round(n);改成result = new Round().round(n);开始result = round(n);往round()方法传入一个ddouble 数1.7,在round()方法里n成了1.0,所以if(((int)(n*10) >= 5)为true,那么返回(int)num+1;因为num是1.7,所以(int)num=1,所以(int)num+1=2.
    我也是刚学Java.
      

  4.   

    我也遇到过这种问题是保留两位小数.我是用了个笨方法拆分字符串来做的...round()方法只能做整数啊.右别的方法么大家推荐下
      

  5.   

    public class Round {
    public static void main(String[] args) {
            double n = 95877445555.01444554;
            int result;
            result = round(n);
            System.out.println(result);
        }
        
        public static int round(double num) {
            double n;
            n = num - (int)num;
            if ((int)(n*10) >= 5)
                return (int)num+1;
            else
                return (int)num;
        }}
    LZ,你定的n足够大,那你的程序就不正确了.
      

  6.   

    public int t(double d){
         return (int)(d + 0.5);
    }
      

  7.   

    public int t(double d){ 
        return (int)(d + 0.5); 
    }