Home > OS >  how to get double to round up to nearest integer?
how to get double to round up to nearest integer?

Time:09-15

the prompt says "Write a program which takes two doubles as input, then prints the sum of the numbers when they are both rounded to their nearest whole number. You may assume the double input is always positive."

what i wrote:

    Scanner scan = new Scanner(System.in);
    System.out.print("Please input two decimal numbers:");
    double hit_1 = scan.nextDouble();
    double hit_2 = scan.nextDouble();
    
    double hit_add = (hit_1   hit_2   0.5);
    System.out.print("Answer: "   (int)hit_1   "   "   (int)hit_2   " = "   (int)hit_add);

for most decimals, it rounds fine, but what i want is for numbers like 4.5 to round to 5. right now, it rounds 4.5 to 4. i added 0.5 in an attempt to get the double to round up, but it didn't work. i'm also not allowed to use Math.round() or anything like that.

CodePudding user response:

create your own round method like this. Convert to int, then find the remainder. If remainder >= 0.5, just add 1 to the integer. See below:

    private static int round(double d){
        int i = (int)d;
        double remainder = d - i;
        if(remainder>=0.5){
            i  ;
        }
        return i;
    }

then you can use that method on your double

CodePudding user response:

just need 0.5:

double a = 1.8, b = 1.2;                                                                                   
System.out.println((int)(a   0.5));                                                                        
System.out.println((int)(b   0.5));
System.out.println((int)(a   0.5)   (int)(b   0.5));

for your code:

Scanner scan = new Scanner(System.in);
System.out.print("Please input two decimal numbers:");
double hit_1 = scan.nextDouble()   0.5;
double hit_2 = scan.nextDouble()   0.5;
int hit_1P2 = (int)hit_1   (int)hit_2;
System.out.print("Answer: "   (int)hit_1   "   "   (int)hit_2   " = "   hit_1P2);

CodePudding user response:

There was two ways where double can be rounded off to nearest integer.

a. Using typecasting to int Example : If double holds value as 3.26, all the digits after decimal are lost.

b. Using Math.round() function - This will add 0.5 to double and rounds to nearest integer.

Example : If double holds value of 3.7, then this function will add 0.5 and rounds to 4 as nearest integer. Similar way, if double value is 3.2, then Math.round() will add 0.5, so this would become 3.7, in this case the nearest integer is still 3

Below is sample code block for above two examples

    double d = 3.5;
    int typeCastInt = (int) d;
    int t = (int) Math.round(d);

    System.out.println(typeCastInt); //prints 3
    System.out.println(t); //Prints 4       
  • Related