可能的重复:
Java 整数除法,如何产生双精度数? https://stackoverflow.com/questions/3144610/java-integer-division-how-do-you-produce-a-double
double wang = 3 / 2;
Log.v("TEST", "Wang: " + Double.toString(wang));
Logcat 输出...
07-04 09:01:03.908: VERBOSE/TEST(28432): Wang: 1.0
我确信这个问题有一个明显的答案,可能我只是因为整夜编码而感到疲倦,但这让我难住了。
In many languages, Java being one of them, the way you write a number in an expression decides what type it gets. In Java, a few of the common number types behave like this1:
// In these cases the specs are obviously redundant, since all values will be
// cast correctly anyway, but it was the easiest way to show how to get to the
// different data types :P
int i = 1;
long l = 1L;
float f = 1.0f; // I believe the f and d for float and double are optional, but
double d = 1.0d; // I wouldn't bet on what the default is if they're omitted...
因此,当你声明3 / 2
,你确实是在说(the integer 3) / (the integer 2)
。 Java 执行除法,结果为1
(i.e. the integer 1
...) 因为这是 3 和 2 除以整数的结果。最后,the integer 1
被投射到the double 1.0d
它存储在您的变量中。
要解决这个问题,您应该(正如许多其他人所建议的那样)计算
(the double 3) / (the double 2)
或者,在 Java 语法中,
double wang = 3.0 / 2.0;
1 Source: The Java Tutorial http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html from Oracle
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)