Home > Net >  How to round up a fraction on java?
How to round up a fraction on java?

Time:09-22

So I'm trying to write a method on java that takes as input two floats that represent two area. It returns the quotient of the division of area1 by area2 rounded up as an integer. Here's my code :

public class PizzaClal {

    public static void main (String[] args){
        System.out.println(round_up(15.0, 6.0));
    }

    static int round_up(double area1, double area2) {
        double diff1 = area1 / area2;
        double diff2 = area2 / area1;

        if (area2 > area1  && diff2 > (int) diff2)  {
            return (int) (diff2)   1;
        }if (area1 > area2 && diff1 > (int) diff1) {
            return (int) (diff1)   1;
        } else{
            return (int) (diff1);
        }
    }
}

It is suppose to return 3 but it return 67. I'm new in java and I only know Python so I don't really understand where's my error. can anyone help me please?

CodePudding user response:

You can greatly simplify your code if you basically just want to return the ceiling of a division result. One trick is to use the modulus operator %, which returns the remainder of division, which is particularly useful here. If the remainder of a / b is non-zero, then b does not divide a evenly. Just adding 1 to the integer division result will produce a "ceiling" result. You can simply cast (area1 / area2) to an integer to acquire the integer division result.

static int round_up(double area1, double area2) {
    int result = (int) (area1 / area2);
    if (area1 % area2 != 0) {
        result  ;
    }
    return result;
}

CodePudding user response:

return Math.ceil(area1/area2);
  • Related