简体   繁体   English

Java int cast返回0

[英]Java int cast returns 0

I have the following code: 我有以下代码:

int i = (int) 0.72;
System.out.println(i);

Which yields the following output: 产生以下输出:

0

I would of imagined that the variable i should have the value of 1 (since 0.72 > 0.5 => 1) , why is this not the case? 我想象变量i应该具有值1 (因为0.72> 0.5 => 1) ,为什么不是这种情况?

(I imagine that when casting to int, it simply cuts of the decimal digits after the comma, not taking into account of rounding up; so I'll probably have to take care of that myself?) (我想,当转换为int时,它只是在逗号之后删除十进制数字,而不是考虑到舍入;所以我可能必须自己处理它?)

Correct, casting to an int will just truncate the number. 正确,转换为int只会截断数字。 You can do something like this to get the result you are after: 你可以做这样的事情来得到你想要的结果:

int i = (int)Math.round(0.72);
System.out.println(i);

This will print 1 for 0.72 and 0 for 0.28 for example. 例如,这将打印1表示0.72和0表示0.28。

Because when you cast a double to int, decimal part is truncated 因为当你将double转换为int时,小数部分会被截断

UPDATE Math.round will give your desired output instead of Math.ceil : UPDATE Math.round将提供您想要的输出而不是Math.ceil

 System.out.println(Math.round(0.72));
// will output 1

 System.out.println(Math.round(0.20));
// will output 0

You can use Math.ceil : 你可以使用Math.ceil

System.out.println(Math.ceil(0.72));
// will output 1
 System.out.println(Math.ceil(0.20));
// will output 1

Casting to an int implicity drops the decimal part. 转换为int implicity会丢弃小数部分。 That's why you get 0 because anything after the 0 is removed (in your case the 72). 这就是为什么你得到0,因为0之后的任何东西都被删除了(在你的情况下是72)。 If you want to round then look at Math.round(...) 如果你想圆,那么看看Math.round(...)

显式转换将float / double值转换为int变量(丢弃小数部分)

Java does not round-off the number like we do.It simply truncates the decimal part. Java不像我们那样舍入数字。它只是截断小数部分。 If you want to round-off the number use java.lang.Math 如果要使用java.lang.Math来舍入数字

Casting double to int truncates the non-integer portion of the number. doubleint截断数字的非整数部分。

To round numbers as you describe, use Math.round() 要按照您的描述对数字进行舍入,请使用Math.round()

As a complete Java beginner, and just in case my experience is useful to someone, I was just making the following mistake: 作为一个完整的Java初学者,以防我的经验对某人有用,我只是犯了以下错误:

int x = (int) Math.random() * 10;

... which will always set x to 0. Instead, I should've done int x = (int) (Math.random() * 10); ...总是将x设置为0.相反,我应该完成int x = (int) (Math.random() * 10); .

Not much of a Java-know-how specific mistake, but I'll just throw this in case anyone puzzled by this stumbles upon this question. 没有多少Java专有技术的错误,但我会抛弃这个,以防任何困惑的人在这个问题上绊倒。

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

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