我的代码存在问题。 它在编译时工作正常,直到我达到数字分割的程度。我没有得到带小数的数字,只有零。如您所见,我已将最后一个变量更改为double,但它没有任何有意义的结果。
我该怎么做才能改变这个?
int[] arr = new int[2];
System.out.println("enter two numbers: ");
arr[0] = sc.nextInt();
arr[1] = sc.nextInt();
int summa = arr[0]+arr[1];
System.out.println("What's "+arr[0]+" + "+arr[1]+" ?");
int vad = sc.nextInt();
if (summa == vad)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is "+summa);
int summa2 = arr[0]-arr[1];
System.out.println("What's "+arr[0]+" - "+arr[1]+" ?");
int vad2 = sc.nextInt();
if (summa2 == vad2)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is: "+summa2);
int summa3 = arr[0]*arr[1];
System.out.println("What's "+arr[0]+" * "+arr[1]+" ?");
int vad3 = sc.nextInt();
if (summa3 == vad3)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is "+summa3);
double summa4 = arr[0]/arr[1];
System.out.println("What's "+arr[0]+" / "+arr[1]+" ?");
double vad4 = sc.nextInt();
if (summa4 == vad4)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is "+summa4);
}
}
答案 0 :(得分:4)
1 您正在阅读 int 它应该 double 。
2 您需要转换为 双 检查以下代码
double summa4 = ((double)arr[0])/arr[1];
System.out.println("What's "+arr[0]+" / "+arr[1]+" ?");
double vad4 = sc.nextDouble();
if (summa4 == vad4)
System.out.println("Correct!");
else
System.out.println("Wrong - The right answer is "+summa4);
答案 1 :(得分:2)
虽然 summa4 变量的类型为double,但它的计算是在整数除法中完成的。因此,结果将没有任何小数位。
例如,如果5和2都是整数或存储在int类型变量中的值,则5/2 = 2而不是2.5。
变化:
double summa4 = arr[0]/arr[1];
到
double summa4 = 1.0*arr[0]/arr[1];