3/2 = 1.0?真? [英] 3 / 2 = 1.0? really?

查看:97
本文介绍了3/2 = 1.0?真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/3144610/java-integer-division-how-do-you-produce-a-double\">Java整数除法,你如何制作一张双人床?


 双王= 3/2;
Log.v(TEST,王+ Double.toString(王));

logcat的输出...

 九月七日至4日:01:03.908:VERBOSE / TEST(28432):王老师:1.0

我敢肯定有一个明显的答案,这或许和我从编码整夜只是累了,但这有我难住了。


解决方案

在许多语言中,Java的是其中之一,你写一个前pression一个编号的方式决定什么类型它得到。在Java中,一些常见的号码类型这样的表现 1

  //在这种情况下,规范显然多余的,因为所有的值会
//正确投反正,但它说明如何获取到的最简单方法
//不同的数据类型:P
INT I = 1;
长L = 1L;
浮动F = 1.0F; //我相信浮动的F和D和双是可选的,但
双D = 1.0D; //我不会赌默认值是什么,如果他们忽略...

因此​​,当你声明 3/2 ,你真的说(整数3)/(整数2)。 Java的执行师,发现得到的结果是 1 (即整数1 ...),因为那是分3和2的整数结果。最后,整数1 被转换为双1.0D 存储在您的变量。

要解决这个问题,你应该(正如许多其他人所说),而不是计算出的商数

 (双3)/(双2)

,或在Java语法,

 双王= 3.0 / 2.0;


1 来源: Java教程从Oracle

Possible Duplicate:
Java Integer Division, How do you produce a double?

double wang = 3 / 2;
Log.v("TEST", "Wang: " + Double.toString(wang));

Logcat output...

07-04 09:01:03.908: VERBOSE/TEST(28432): Wang: 1.0

I'm sure there's an obvious answer to this and probably I'm just tired from coding all night but this has me stumped.

解决方案

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...

Thus, when you declare 3 / 2, you're really saying (the integer 3) / (the integer 2). Java performs the division, and finds the result to be 1 (i.e. the integer 1...) since that's the result of dividing 3 and 2 as integers. Finally, the integer 1 is cast to the double 1.0d which is stored in your variable.

To work around this, you should (as many others have suggested) instead calculate the quotient of

(the double 3) / (the double 2)

or, in Java syntax,

double wang = 3.0 / 2.0;


1 Source: The Java Tutorial from Oracle

这篇关于3/2 = 1.0?真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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