Reputation: 161
Trying to write this script that works with inputs that often go up into hundreds of billions. However, Math.ceil won't round upwards?
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. As you can see clayneeded isn't blank. As if that's the case then clayturns should always be something, it can't be zero, but it is.
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?
Upvotes: 1
Views: 744
Reputation: 51
This is because you store your clayturns variable inside an integer. There is an Integer overflow happening, which returns 0.
The maximum value for an integer is +2,147,483,647.
Upvotes: -1
Reputation: 36401
Looks like clayneeded
has integer type (probably long
). So clayneeded/7500000000L
is integer division (quotient), thus ceil
computes the ceiling of an integer, so itself.
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) :
long remainder = clayneeded % 7500000000L;
long result = (clayneeded/7500000000L)+(remainder!=0?1:0);
Upvotes: 0
Reputation: 607
is clayneeded
an int
/long
? if you're doing int
/long
division, it'll truncate any fractional component before it gets to the 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.
Upvotes: 3