If语句使用数组控制数字范围

时间:2018-11-14 12:01:57

标签: c++ arrays if-statement

我创建了一个包含5个数字的数组,用户输入了数字。如果标记小于0且大于100,我想打印出“无效标记号”。我该怎么办?

using namespace std; 

int mark[5];

int main () 
{
cout << "enter mark 0:  ";
cin >> mark[0];


cout << "enter mark 1:  ";
cin >> mark[1];

cout << "enter mark 2:  ";
cin >> mark[2];

cout << "enter mark 3:  ";
cin >> mark[3];

cout << "enter mark 4:  ";
cin >> mark[4];

}

1 个答案:

答案 0 :(得分:1)

您应该使用for-loop使代码更具可读性和紧凑性。因为一旦引入if语句,代码大小就会大量增加。它应该看起来像这样:

#include <iostream>

using namespace std;

int mark[5];

int main () {
    for (int i = 0; i < 5; i++){
        cout << "enter mark " << i << ":  ";
        cin >> mark[i];
        if (mark[i] < 0 || mark[i] > 100){
            cout << "invalid mark number\n";
        }
    }
}

请勿使用using namespace std;read here why)并将int mark[5];保留在main函数(read here why)中。还要添加逻辑以强制用户再次输入:

#include <iostream>

int main () {
    int mark[5];
    for (int i = 0; i < 5; i++){
        bool valid_input = false;
        while (!valid_input){
            std::cout << "enter mark " << i << ":  ";
            std::cin >> mark[i];
            if (mark[i] < 0 || mark[i] > 100){
                std::cout << "invalid mark number\n";
            }
            else{
                valid_input = true;
            }
        }
    }
}