[英]Why isn't math.ceiling rounding up my number? java
Trying to write this script that works with inputs that often go up into hundreds of billions. 尝试编写此脚本,使其能够处理通常高达数千亿美元的输入。 However, Math.ceil won't round upwards? 但是,Math.ceil不会向上舍入吗?
int clayturns = (int)Math.ceil(clayneeded / 7500000000L);
System.out.println((int) Math.ceil(clayneeded / 7500000000L));
System.out.println("we need " + clayturns + "turns");
System.out.println("we need " + clayneeded + " clay added to our specific village.");
under here I have the eclipse console output. 在这里,我有eclipse控制台输出。 As you can see clayneeded isn't blank. 如您所见,clayneeded不是空白。 As if that's the case then clayturns should always be something, it can't be zero, but it is. 好像是这种情况,那么clayturns总是应该是某种东西,它不能为零,但它是零。
we need 0turns
we need 3021588634 clay needed to our specific village.
Please let me know what you think. 请让我知道你的想法。 Does math ceil not work with Longs? 数学单元格不适用于Longs吗?
is clayneeded
an int
/ long
? 被clayneeded
的int
/ long
? if you're doing int
/ long
division, it'll truncate any fractional component before it gets to the Math.ceil
. 如果您要进行int
/ long
除法,则它将截断任何小数部分,然后再到达Math.ceil
。 Given the size of your inputs, I'd stay away from float
s/ double
s, and use BigDecimal
s to do the math accurately here. 给定您输入的大小,我将远离float
s / double
,并在这里使用BigDecimal
进行精确的数学运算。
Looks like clayneeded
has integer type (probably long
). 看起来clayneeded
具有整数类型(可能是long
)。 So clayneeded/7500000000L
is integer division (quotient), thus ceil
computes the ceiling of an integer, so itself. 因此clayneeded/7500000000L
是整数除法 (商),因此ceil
计算整数的上限,即整数。
So you can compute it like this (if the remainder of the integer division is not nul then the ceiling must produce the next integer) : 因此,您可以这样计算(如果整数除法的余数不是nul,则上限必须产生下一个整数):
long remainder = clayneeded % 7500000000L;
long result = (clayneeded/7500000000L)+(remainder!=0?1:0);
This is because you store your clayturns variable inside an integer. 这是因为您将clayturns变量存储在整数内。 There is an Integer overflow happening, which returns 0. 发生整数溢出,返回0。
The maximum value for an integer is +2,147,483,647. 整数的最大值为+2,147,483,647。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.