在Java中使用算术运算符将两个数相除。

Scanner scan = new Scanner(System.in);
System.out.print("Write a number: ");
String mataett = scan.next();
System.out.print("Write a number: ");
String matatva = scan.next();

int nr1 = Integer.parseInt(mataett);
int nr2 = Integer.parseInt(matatva);
System.out.println(Math.round(nr1 / nr2*10.0)/10.0);


当我用73/27运行时,我得到的答案是2.0,但是我想得到的是答案2.7

最佳答案

当我以73/27运行时,得到的答案是2.0,但是我想要
  得到答案2.7


之所以得到意想不到的结果,是因为当您将其除以整数时,结果始终是整数,这意味着小数点后的任何数字都会被截断。

nr1 / nr2 // <-- this part within the calculation is causing the problem.


解决这个问题的一个简单技巧是先将整数nr1nr21.0相乘,然后应产生一个双精度数,这将使您保持精度,因为您要除以现在是double而不是int

例:

System.out.println(Math.round((1.0 * nr1) / nr2 * 10.0)/10.0);


注意1.0

关于java - 除数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43300892/

10-12 19:55