在C ++上运行程序,如果正确,否则再次询问输入

时间:2016-09-23 03:46:44

标签: c++ while-loop

我是编程的新手。我正在开发一个程序,它会告诉奇数和偶数数字是否小于或等于用户的输入(输入&gt; = 0)。如果值为&gt; = 0,如何使程序运行,如果值<0,则再次请求输入。 这是程序:

> #include <iostream>
using namespace std;
int main() {
    cout << "Please enter only a positive value\n";
    // Get number from user
    int input = 0;
    cout << "Enter a number:\n";
    cin >> input;
    int number = 1;
    while (input >= 0 && number <= input) {
        // Print some numbers
        cout << "Here are some odd numbers:\n";
        while (number <= input) {
            cout << number << endl;
            number = number + 2;
        }
        // Print some numbers
        cout << "Here are some even numbers:\n";
        int number2 = 0;
        while (number2 <= input) {
            cout << number2 << endl;
            number2 = number2 + 2;
        }
    }
    return 0;
}

2 个答案:

答案 0 :(得分:0)

while (input < 0)
{
    cout << "Enter a number:\n";
    cin >> input;
    if (input < 0) 
        // Here you can print something to tell that input was not correct
}

答案 1 :(得分:0)

正确的代码:

#include <iostream>
using namespace std;
int main() {
    cout << "Please enter only a positive value\n";
    // Get number from user
    int input = 0;
    cout << "Enter a number:\n";
    cin >> input;
    while (input < 0) {
        cout << "Input is negative. Enter again: \n";
        cin >> input;
    }
    int number = 1;
    while (input >= 0 && number <= input) {
        // Print some numbers
        cout << "Here are some odd numbers:\n";
        while (number <= input) {
            cout << number << endl;
            number = number + 2;
        }
        // Print some numbers
        cout << "Here are some even numbers:\n";
        int number2 = 0;
        while (number2 <= input) {
            cout << number2 << endl;
            number2 = number2 + 2;
        }
    }
    return 0;
}

请注意,我添加了这个块:

while (input < 0) {
     cout << "Input is negative. Enter again: \n";
     cin >> input;
}

处理负面投入。