C++:如果用户输入的数字错误,则要求用户输入新号码

ckn*_*nox 0 c++ for-loop if-statement

我试图让程序再次循环,最多三次,如果用户输入的数字不遵循if语句中定义的函数.代码原样,只循环一次然后退出.我是否for错误地键入了循环if...else,还是错误的陈述?

#include <iostream>

using std::cout; using std::cin; using std::endl;

int main() {
    cout << "Enter a positive odd number less than 40: ";
    int num = 0;


    for (int a = 0; a < 3; ++a);
    cin >> num;
    {   
        if (num < 40 && num > 0 && num % 2 == 1)
        {
            cout << "Thank you!" << endl;
        }
        else cout << "That is incorrect, try again!" << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

我是否错误地输入了for循环,还是if _ else语句错了?

都.您应该(1)删除该for声明后的分号; (2)cin >> num进入for循环体; (3)加入break;里面if.

for (int a = 0; a < 3; ++a)
{   
    cin >> num;
    if (num < 40 && num > 0 && num % 2 == 1)
    {
        cout << "Thank you!" << endl;
        break;
    }
    else cout << "That is incorrect, try again!" << endl;
}
Run Code Online (Sandbox Code Playgroud)

BTW1:尝试使用调试器,然后你会发现事实上发生了什么.

BTW2:代码将在失败时cin >> num失败(例如,用户输入了无效值),您可能需要检查结果cin >> num,以处理案例.如:

for (int a = 0; a < 3; ++a)
{   
    if (cin >> num) 
    {
        if (num < 40 && num > 0 && num % 2 == 1)
        {
            cout << "Thank you!" << endl;
            break;
        }
        else cout << "That is incorrect, try again!" << endl;
    }
    else 
    {
        cin.clear(); // unset failbit
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
        cout << "Wrong input, try again!" << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)