我正确处理这个浮点变量吗?

时间:2015-02-20 19:23:47

标签: java

我想确保float变量resultd的初始化是正确的。因为它是错误所在。

static void caculateValues() {


    int a, b;
    int resulta, results, resultm;
    float resultd;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a:");
    a = sc.nextInt();
    System.out.print("Enter b:");
    b = sc.nextInt();
            {  

   //This is the only part I edited//

   resulta= a+b;
   results=a-b;
   resultm= a * b;
   resultd= a / b;

   //This is where I stopped editing//
    }    


    System.out.println("The result of adding is " + resulta);
    System.out.println("The result of subtracting is " + results);
    System.out.println("The result of multiplying is " + resultm);
    System.out.println("The result of dividing is " + resultd);


}

他们声称我的输出应该是这样的:

(a = -50) (b = -20) 
The result of adding is -70
The result of subtracting is -30
The result of multiplying is 1000
The result of dividing is 2.5

但据说我的输入显示:

The result of adding is -70
The result of subtracting is -30
The result of multiplying is 1000
The result of dividing is 2.0

1 个答案:

答案 0 :(得分:1)

即使resultdfloat,您仍然会将两个int分开:

a / b

在Java中,2 int s的除法必须是int。这就是2.0出现的原因。 Java中-50 / -202,而非2.5。只有在2生成后,才会在分配到float后将其提升为resultd

将其中一个变量强制转换为float,从一开始就强制使用浮点数学。

resultd = (float) a / b;

您可以轻而易举地resultd double并将a转换为double