如果有四个输入,如何使用switch语句

时间:2016-01-06 09:37:42

标签: c++

一个班级在一个学期内有四门考试。输入每个考试分数并分配相应的分数。

90及以上是A
B至80为89 70至79是C
D至60为69至69 低于60是F
低于0

我只能使用1输入而不是4

进行编码
#include<iostream>
using namespace std;
int main(){

int a;

cout<<"Input Examination Score: ";
cin>>a;

switch (a / 10){
case 0: 
case 1: 
case 2: 
case 3:
case 4:
case 5: cout <<"Equivalent is F"<<endl;
break;
case 6: cout <<"Equivalent is D"<<endl;
break;
case 7: cout <<"Equivalent is C"<<endl;
break;
case 8: cout <<"Equivalent is B"<<endl;
break;
case 9:
case 10: cout <<"Equivalent is A"<<endl;
break;
default: cout <<"Invalid Score"<<endl;
break;
}

2 个答案:

答案 0 :(得分:0)

您可以通过不同方式执行此操作。您可以使用for循环或while / do-while循环。

for(int i = 0; i < 4; i++) // runs 4 times
{
    //Do your thing
}

或者您可以创建值为4的变量,使用while / do-while循环 并且每学期减1,直到它为0。

答案 1 :(得分:0)

使用循环多次读取输入,然后计算打印结果时的平均值:

#include<iostream>

using namespace std;

int main(){

    int number_grades = 4;
    int sum = 0;

    for (int i=0; i<number_grades; ++i) {
        int a;
        cout<<"Input Examination Score: ";
        cin>>a;
        sum +=a;
    }

    switch ((sum/number_grades) / 10){
    case 0: 
    case 1: 
    case 2: 
    case 3:
    case 4:
    case 5: cout <<"Equivalent is F"<<endl;
        break;
    case 6: cout <<"Equivalent is D"<<endl;
        break;
    case 7: cout <<"Equivalent is C"<<endl;
        break;
    case 8: cout <<"Equivalent is B"<<endl;
        break;
    case 9:
    case 10: cout <<"Equivalent is A"<<endl;
        break;
    default: cout <<"Invalid Score"<<endl;
        break;

    }

    return 0;
}