Rounding Problem 7 (JAVA HELP)

Back to General discussions forum

Java_Coder     2015-05-24 21:34:08

I have been doing this problem, and it doesn't really make sence. If someone could explain how this program is supposed to run that would be awesome. Here is the code that I have so far, some advice on how close I am is greatly appreciated.

package Projects; import java.util.Scanner;

public class Rounding {

public static void main(String[] args) 
{
    Scanner scan = new Scanner(System.in);

    System.out.println("data: ");

    int n = scan.nextInt();
    int round = 0;
    for(int i = 0; i < n; i++)
    {
        int x = scan.nextInt();
        int y = scan.nextInt();

        if(round>0.5)
            round = (int) (x/y)+1;
        else
            round = (int) (x/y);
        System.out.println( round);
    }




}

}

Thanks in advanced. -Java_Coder

ndon55555     2015-05-26 05:22:02
User avatar

I'm not exactly sure what you're doing here, but for rounding a number, try this:

public static int round(double n){
    return (int) n + 0.5; 
}

You can also use Math.round(n) where n is the number you want to round.

OldProgrammer     2015-05-26 21:50:31

Java Coder: rounding depends on the fractional part.

If you have 3 / 2 = 1.5 the result is 2 because the fractional part is at least 0.5. If you have 4 / 3 = 1.3333 the result is 1 because the fractional part 0.3333 < 0.5.

The round variable isn't really doing anything in your program. Also, the program has x and y as ints so x / y is integer division which truncates the fractional part e.g. 3 / 2 = 1 with integer division.

You need to do the division using floating point types to keep the fractional part and then do the rounding.

Please login and solve 5 problems to be able to post at forum