Home > database >  Check which number nearest to the value 0 among two given integers
Check which number nearest to the value 0 among two given integers

Time:02-27

I have 2 integers:

int number1 = 45;
int number2 = 40;

Now I want to compare both and check which one is nearer to the number 0.

As output I want true / false.

For example:

if (compare(number1, number2))
{
    console.write("number1 is nearer to 0");
}
else
{
    console.write("number2 is nearer to 0");
}

Output:

number 2 is nearer to 0

CodePudding user response:

You shold use ABS, before compare.

CodePudding user response:

int compare(int a, int b)  {
    if (abs(a) > abs(b)){
        std::cout <<b <<" is closer to zero" <<std::endl ;
        return b;
    }
    else{
        std::cout <<a <<" is closer to zero" <<std::endl ;
        return a;
    }
}

This function might be helpful for you. It both displays the answer in the terminal and returns the int value which is closer to 0 in order to be used by other parts of your program.

CodePudding user response:

I'm assuming you want the actual function 'compare', and that the integers can be negative

int compare(int number1, int number2) {
    return abs(number1) < abs(number2);
}
  • Related