-1

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 Answers1

5

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);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thank you. It's still not completely perfect, I'm having to input one more number even though the condition is met, but it's working and I'm on the right track now. – JigglyBlubber Mar 07 '17 at 06:09
  • @JigglyBlubber, that does not sound right. You shouldn't have to input any more numbers after the conditional in the `do { .. } while ();` statement is met. – R Sahu Mar 07 '17 at 06:13