简体   繁体   English

Java为什么我的计算不能用于此代码?

[英]Java why doesn't my calculation work on this code?

Hi I'm trying to run a calculation but I can't seem to put it all on one line, I have to split the result into two seperate lines to achieve the desired result (which seems a bit long winded). 嗨我正在尝试运行计算,但我似乎无法将它全部放在一行上,我必须将结果分成两个单独的行来实现所需的结果(这看起来有点长啰嗦)。 Can anyone explain where I'm going wrong? 谁能解释我哪里出错?

both x and y are doubles. x和y都是双打。

Example 1: (incorrect) 例1 :(不正确)

y=0.68
x= (Math.round(y* 10))/10;
result x=0

Example 2: (correct) 例2 :(正确)

y=0.68
x= Math.round(y* 10);
x = x/10;
result x=0.7

thanks for your time. 谢谢你的时间。

Math.round returns variable of type long (see: Javadoc ), which means that the division by 10 is performed on a long variable resulting in another long variable - that's why you lose the precision. Math.round返回long类型的变量(参见: Javadoc ),这意味着除以10的除法是对一个long变量执行的,导致另一个long变量 - 这就是你失去精度的原因。

To make it calculate on it as on double and return double - you have to cast the result of Math.round like this: 要使它计算为double并返回double - 你必须像这样抛出Math.round的结果:

x= ((double)Math.round(y* 10))/10;

Have you tried to explicitly specify double in your calculation: 您是否尝试在计算中明确指定double:

x = ((double)Math.round( y * 10.0)) / 10.0;

Math.round returns a long.... Math.round返回很长的....

It's hard to tell from your snippets, because they don't include variable types, but it's likely to be integer division that's killing you. 很难从你的片段中分辨出来,因为它们不包含变量类型,但它可能是整数除法,它会杀死你。 When you divide two integers x and y, where x < y, you get zero: 除以两个整数x和y,其中x <y,得到零:

int x = 4;
int y = 10;
int z  = x/y; // this is zero.

When you write: 当你写:

double x = (Math.round(y* 10))/10;

(Math.round(y* 10)) is a long (= 7), which you divide by 10, that gives another long (= 0). (Math.round(y* 10))是一个long(= 7),除以10,得到另一个long(= 0)。 The result is then converted back to a double and stored in x. 然后将结果转换回double并存储在x中。

In your second snippet: 在你的第二个片段中:

double x = Math.round(y* 10);

This is equal to 7 and converted into a double. 这等于7并转换为double。 x / 10 is then a double operation that returns 0.7. 然后x / 10是一个返回0.7的双重操作。

y=0.68
x= (Math.round(y* 10)) <--- Evaluated as int since Math.round returns int /10; <-- integer division
result x=0


y=0.68
x= Math.round(y* 10) <-- x is stored as double
x = x/10; <-- double division
result x=7

I guess it's because Math.round returns either a long or an int, depending on whether y is double or float. 我想这是因为Math.round返回long或int,具体取决于y是double还是float。 an then you have an integer division. 那么你有一个整数除法。 in the second example x is already a double and that's why you have a double division. 在第二个例子中,x已经是一个双倍,这就是为什么你有一个双重划分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM