简体   繁体   English

Java显式类型转换给出不同的结果

[英]java explicit type conversion gives different results

I would like to know in which order does the explicit type conversion work and in what area does it work. 我想知道显式类型转换按什么顺序工作以及在什么区域工作。 In the next example I receive different results. 在下一个示例中,我收到不同的结果。

float S = 0;
for (int i = 1; i <= 10; i++)
    for (int j = 3; j <= 20; j++)
        S += (i * j - 5.)/(2. * i + j / 3);

the result is 621.8933 结果是621.8933

float S = 0;
for (float i = 1; i <= 10; i++)
    for (float j = 3; j <= 20; j++)
        S += (i * j - 5)/(2. * i + j / 3);

S = 607.3105 S = 607.3105

float S = 0;
for (int i = 1; i <= 10; i++)
    for (int j = 3; j <= 20; j++)
        S += (float)(i * j - 5)/(2 * i + j / 3);

S = 621.8933 S = 621.8933

float S = 0;
for (int i = 1; i <= 10; i++)
    for (int j = 3; j <= 20; j++)
        S += (i * j - 5)/(2 * i + j / 3.);

S = 607.3105 S = 607.3105

Obviously the correct result is 607.3105. 显然正确的结果是607.3105。 Why doesn't it promote when I write (float) or multiply by 2., but it works when I divide by 3.? 为什么当我写(浮点数)或乘以2时,它没有提升,但是当我除以3时,它为什么起作用? Thanks in advance. 提前致谢。

Code 1 S += (i * j - 5.)/(2. * i + j / 3); 代码1 S += (i * j - 5.)/(2. * i + j / 3); :

  • j is an int , thus complete divisor is int and an implicit cast to int is performed j是一个int ,因此完整的除数是int并执行对int的隐式转换

Code 2 S += (i * j - 5)/(2. * i + j / 3); 代码2 S += (i * j - 5)/(2. * i + j / 3);

  • j , x are floats and all consecutive results are floats too jx是浮点数,所有连续结果也是浮点数

Code 3 S += (float)(i * j - 5)/(2 * i + j / 3); 代码3 S += (float)(i * j - 5)/(2 * i + j / 3);

  • j is an int , thus complete divisor is int and an implicit cast to int is performed j是一个int ,因此完整的除数是int并执行对int的隐式转换
  • The explicit float - is performed after computing of the divisor 显式float -在计算除数之后执行

Code 4 S += (i * j - 5)/(2 * i + j / 3.); 代码4 S += (i * j - 5)/(2 * i + j / 3.);

  • Due to '3.' 由于“ 3”。 the divisor becomes of type 'double' 除数变为“ double”类型

Note that 3. is a double, 3.f is a float. 请注意, 3.是双精度型, 3.f是浮点型。 This results in usage of different precision within the operation. 这导致在操作内使用不同的精度。

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

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