C++ Why does my do-while loop fail to end as soon as boolean condition is met?

191 Views Asked by At

My current project calls for a program using a do-while loop and a separate value producing function. The program asks for an indefinite amount of inputs until the difference between the last two numbers entered is greater than 12. The code works but only when it feels like it apparently. Sometimes it recognizes that the bool has been met immediately and terminates, other times I can enter 15+ numbers until it ends, if it even ends in the first place. I'd like to keep my code as similar as I have it currently if that's possible. I know I need a precondition since the first input has nothing to be compared to and I'm trying to figure that out at the moment.

This is my code so far:

bool TwelveApart(int x, int y);

int main()
{
    int num1, num2;
    cout << "Enter some integers: " << endl;

    do
    {
        cin >> num1 >> num2;
        TwelveApart(num1, num2);
    } while (TwelveApart(num1, num2) == false);
    cout << "The difference between " << num1 << " and " << num2 << " is greater than or equal to 12." << endl;

    return 0;
}
bool TwelveApart(int x, int y)
{
    if (abs(x - y >= 12))
    {
        return true;
    }
    else
    {
        return false;
    }
}
1

There are 1 best solutions below

2
On

The conditional in

if (abs(x - y >= 12))

is not setup right. It needs to be:

if (abs(x - y) >= 12 )

FWIW, you can simplify the function to:

bool TwelveApart(int x, int y)
{
   return (abs(x - y) >= 12 );
}

Also, you have a redundant call to TwelveApart in the do-while loop. That call does not do anything useful. The loop can be:

do
{
    cin >> num1 >> num2;
} while (TwelveApart(num1, num2) == false);