[英]Why double width = 50/110000; the output is 0.000000000000000?
This is my code : 这是我的代码:
double width = 50/110000;
System.out.println("width ori is "+width );
And the output is: 0.00000000000
输出为:
0.00000000000
What's wrong ? 怎么了 ? the expected output has to be
4.5454545454545455E-4
预期产量必须为
4.5454545454545455E-4
Any body can explain to me why? 任何人都可以向我解释原因吗?
Because you're dividing two integers, so it will only take the integer part (integer division). 因为你要划分两个整数,所以它只取整数部分(整数除法)。
Dividing integers in a computer program requires special care.
在计算机程序中划分整数需要特别小心。 Some programming languages, treat integer division (ie by giving the integer quotient as the answer).
一些编程语言,处理整数除法(即通过给出整数商作为答案)。 So the answer is an integer.
所以答案是整数。
Examples : 例子 :
In real life In Java
4/3 = 1.33333 4/3 = 1
25/12 = 2.083333 25/12 = 2
9/2 = 4.5 9/2 = 4
50/110000 = 0.000454545 50/110000 = 0
You can cast one of the number (or both but it's actually useless) to double
to avoid that : 您可以将其中一个(或两个但实际上没用)强制转换为
double
以避免:
double width = (double)50/110000;
double width = 50d/110000;
double width = 50.0/110000;
Result of int/int
returns you an integer
. int/int
结果返回一个integer
。
So the decimal part got truncated resulting you with an integer 所以小数部分被截断,导致你得到一个整数
You need to cast: 你需要施放:
double width = (double)50/110000;
As @Josh M has pointed, You can also try : 正如@Josh M指出的那样,您也可以尝试:
double width = 50d / 110000d;
Explanation to what's happening: 解释发生了什么:
In Java, the default type of numbers is int
, so when you write 50/110000
, they're both considered int
, although you defined the result to be double
. 在Java中,默认的数字类型是
int
,因此当您编写50/110000
,它们都被视为int
,尽管您将结果定义为double
。
When int
division occurs, the result will be 0
, because they are both int
s, then the double
will hold this value, which will be represented as double
, so you're getting 0.000000
. 当
int
除法发生时,结果将为0
,因为它们都是int
,然后double
将保持这个值,它将表示为double
,因此你得到0.000000
。
Possible solutions: 可能的解决方案:
d
: 50d/110000d
. d
: 50d/110000d
编码这些数字。 (double)50/110000
. (double)50/110000
。 50.0/110000
. 50.0/110000
。 See Chapter 5. Conversions and Promotions , it'll really help you. 请参阅第5章转换和促销 ,它真的会对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.