为什么Bike2.getTime()返回0而不是正确的整数值?

时间:2015-09-02 12:35:48

标签: java

嘿伙计我正在学习java我写了这个简单的代码我找不到任何错误。我无法获得Bike2 .getTime。感谢您的阅读

public class ConstructorEx3 {

        int Speed;
        int Distance;
        int Minute;
        public int getTime (){
            return  ((Distance/Speed)*Minute);  
        }
        ConstructorEx3 (){
            Distance = 60;
            Speed    = 30;
            Minute   = 60;
        }
        ConstructorEx3 (int D, int S, int M){
            Distance = D;
            Speed    = S;
            Minute   = M;
        }
        public static void main (String []arsh){
            ConstructorEx3 Bike1,Bike2;
            Bike1 = new ConstructorEx3();
            Bike2 = new ConstructorEx3(40,80,60);

        System.out.println("Bike one is travelling at : "+ Bike1.getTime());
        System.out.println("Bike two is travelling at : "+ Bike2.getTime());

        }
}

2 个答案:

答案 0 :(得分:4)

因为整数操作(40/80)*60会给你0。请注意,在整数计算中,40/800而非0.5,您需要在程序中使用double值而不是int来获得准确答案(< em>针对您的具体案例)。

约定相关的一些建议

  • 为您的班级选择有意义的名称来描述其目的,即TimeCalculatorBike
  • 使用小写字母distance而非Distance
  • 启动变量名称
  • 同样,实例变量名称也应以小写字母bike1开头,而不是Bike1
  • 最好在构造函数中使用this.distance而不是Distance = D

答案 1 :(得分:0)

Distance = 40;
Speed = 80;
Minute - 60;

Distance / Speed = 0.5;

由于您使用的是int,因此.5是级联的。最后,获得0 * Minute = 0 * 60 = 0;

最好的方法是将值转换为double并转换回来。请注意,由于在处理double到int转换时没有获得准确的结果,因此它有损。

了解我如何使用getTime()方法解决您的问题:

public class ConstructorEx3 {

        int Speed;
        int Distance;
        int Minute;
        public int getTime (){
            double v = ((double)Distance/(double)Speed);
            v= v * (double)Minute;
            return (int)v;
//          return  ((Distance/Speed)*Minute);    
        }
        ConstructorEx3 (){
            Distance = 60;
            Speed    = 30;
            Minute   = 60;
        }
        ConstructorEx3 (int D, int S, int M){
            Distance = D;
            Speed    = S;
            Minute   = M;
        }
        public static void main (String []arsh){
            ConstructorEx3 Bike1,Bike2;
            Bike1 = new ConstructorEx3();
            Bike2 = new ConstructorEx3(40,80,60);

        System.out.println("Bike one is travelling at : "+ Bike1.getTime());
        System.out.println("Bike two is travelling at : "+ Bike2.getTime());

        }
}

输出:

Bike one is travelling at : 120 
Bike two is travelling at : 30