有关使用Double变量进行Java计算的初学者查询 [英] Beginner query regarding Java calculation using Double variable

查看:76
本文介绍了有关使用Double变量进行Java计算的初学者查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑,也许有人能够解释它;在以下3个命令中...

Hi, I am a bit confused with something, perhaps somebody is able to explain it; in the following 3 commands ...

double z1 = (double) ( 12 / 5 );
System.out.println( z1 ); // = 2.0





double z2 = 12 / 5;
System.out.println( z2 ); // = 2.0





double z3 = (double) 12 / 5 ;
System.out.println( z3 ); // = 2.4



...似乎只有第三个可以正确计算.

如果将变量定义为Double,是否不告诉系统它是带有小数位的数字变量?如果是这样,为什么前2条语句给出的结果不正确?!?



... only the third one seems to do the correct calculation.

If a variable is defined as a Double, are you not telling the system that it is a numeric variable with decimal places ? If so, why do the first 2 statements give an incorrect result ?!?

推荐答案

答案很简单.在前两种情况下,表达式12 / 5被视为整数除法,因为这是计算它的最小必要".随后将结果转换为double不会影响对其进行评估的方式.
在第三种情况下,您要求将(double) 12除以(整数)5,因此在将5提升为两倍后,除法必须为12.0 / 5.0.

查看关于表达式评估的任何教程(甚至不必是Java的-几乎所有与C有任何关系的现代过程语言都使用基本上相同的规则).

彼得
The answer is simple. In the first two cases, the expression 12 / 5 is treated as integer division, as that is the "minimum necessary" to calculate it. Subsequent conversion of the result to double doesn''t affect how it was evaluated.
In you third case, you are asking to divide (double) 12 by (integer) 5, so the division has to be 12.0 / 5.0 after the 5 is promoted to double.

Look at any tutorial about expression evaluation (it doesn''t even have to be for Java - almost all modern procedural languages that bear any relationship to C use essentially the same rules).

Peter


这篇关于有关使用Double变量进行Java计算的初学者查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆