我想确保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
答案 0 :(得分:1)
即使resultd
是float
,您仍然会将两个int
分开:
a / b
在Java中,2 int
s的除法必须是int
。这就是2.0
出现的原因。 Java中-50 / -20
为2
,而非2.5
。只有在2
生成后,才会在分配到float
后将其提升为resultd
。
将其中一个变量强制转换为float
,从一开始就强制使用浮点数学。
resultd = (float) a / b;
您可以轻而易举地resultd
double
并将a
转换为double
。