Friday, January 20, 2012

How do i round up in integer division in Java?

I'm writing a simple program for my intro to comp sci class. All it is is a unit converter and the only problem is he wants us to use integers rather than longs/doubles. He also wants us to correct any rounding errors but i'm having trouble getting them to round up. He mentioned in class something about adding 0.5 to the number so when it rounds down, if the number were 1.7, it would become 2.2 and correctly round down to 2. But.... you can't add .5 to an integer...



Any solutions?How do i round up in integer division in Java?
Apart from using Andrew's advice, are you able to use a double for the rounding (adding 0.5) and then convert this back to the integer?



Anyhow, in the example you have given, 1.7 is a double (or float), so I can't see why you can't use a double (or float) to make the initial add of 0.5 and then convert it back to an int.



The reason I say this is there is no other way to add 0.5 or to get 1.7



Example

double input = 1.7; // You get this number from user input or something.

input = input + 0.5;

int rounded = (int) input;



or

int original = 17;

double temp = 17 / 10;

temp = temp + 0.5;

int rounded = (int) temp;



The variable rounded will have a value of 2.



If you are not allowed to use doubles at all, you could possibly do something like this.

int original = 17;

int divisor = 10; // Change this to whatever you are dividing the original by.

original = original * 10; // This is making the int times 10 for the next line.

original = original + 5; // This is adding 0.5 * 10.

int divided = orginal / divisor;

int rounded = divided / 10; // To negate the original times by 10 to add 5 to the number.





Hope that helpsHow do i round up in integer division in Java?
adapt this



int x = 3;

int y = 2;

if (x%y != 0)

{

int z = x/y;

z++;

}

else

int z = x/y;



you can have the user input the numbers using a Scanner

Scanner key = new Scanner(System.in);

in the first if statement:

1. it checks to see if x is divisible by y

2. if it isnt then it will do integer division

3. and because it isnt divisible, it will round down, so i added 1 to it



if you are allowed to use casts:



int x = 3;

int y = 2;

System.printf("%.0f",(double)x/y);



it is actually an int, just casted to a double. use this if and only if you can use casts... much more accurate.



good luck

No comments:

Post a Comment