简体   繁体   English

C ++为什么一旦满足布尔条件,我的do-while循环就无法结束?

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

My current project calls for a program using a do-while loop and a separate value producing function. 我当前的项目需要使用do-while循环和单独的值产生函数的程序。 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. 程序要求输入无限数量的输入,直到最后输入的两个数字之间的差大于12。该代码有效,但仅在看起来很明显的情况下。 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. 有时它会识别出布尔已被立即满足并终止了,有时我可以输入15个以上的数字,直到终止为止,即使它排在首位也是如此。 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;
    }
}

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: FWIW,您可以将功能简化为:

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

Also, you have a redundant call to TwelveApart in the do-while loop. 另外,您可以在do-while循环中对TwelveApart进行冗余调用。 That call does not do anything useful. 该调用没有任何用处。 The loop can be: 循环可以是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM