为什么我的switch语句不能正常工作?

时间:2019-02-05 07:17:31

标签: c++

在我的switch语句中,有3个选项2正常工作,第三个选项显示了我在第二个而不是自己的代码中写的内容。

我尝试使用情况1 :,情况2 :,但说情况2:不在switch语句中。

int main()

{
int choice;
char y;

do
{
    cout << "1. BSEE" <<endl;
    cout << "2. BSIE-ICT" <<endl;
    cout << "3. BGT-AT" <<endl;
    cout << endl;
    cout << "Choose your Course" <<endl;
    cout << endl;
    cin >> choice;
    cout << endl;
   switch (choice)
{

cout << "Welcome to GPA Calculator" <<endl;
cout << endl;
cout << "Grade Equivalent (A=1, B=1.25, C=1.5, D=1.75, E=2., F=2.25, G=275, H=2.75, I=3, J=5" << endl;


double numericGrade[10];
string courses[10] = { "BES1", "CHEMENG", "CHEMLAB", "ESW", "GEC5", "GEC6", "GEC7", "MATHENG", "NSTP", "PE" };
int creditForCourses[10] = { 1, 3, 1, 2, 3, 3, 3, 3, 3, 2 };
double gpa = 0.00;
int i;

    for (i = 0; i < 10; i++) {
    if (letterGrade[i] == "A") {
        numericGrade[i] = 1;
        }
        else
        if (letterGrade[i] == "B") {
        numericGrade[i] = 1.25;
        }
        else
        if (letterGrade[i] == "C") {
        numericGrade[i] = 1.5;
        }

 }

    for (i = 0; i < 10; i++) {
        gpa += (numericGrade[i] * creditForCourses[i]);
    }

    gpa /= 27;

    cout << "Your GPA is: " << gpa << endl;

    break;
}
{


string letterGrade[10]; 
double numericGrade[10];
string courses[10] = { "GEC4", "GEC5", "HE1E", "HE1EL", "ICT1E", "ICT1EL", "NSTP1", "PE1", "PIE1", "PI2" };
int creditForCourses[10] = { 3, 3, 3, 1, 3, 3, 3, 2, 3, 3 };
double gpa = 0.00;
int i;
  }

    for (i = 0; i < 10; i++) {
    if (letterGrade[i] == "A") {
        numericGrade[i] = 1;
        }
        else
        if (letterGrade[i] == "B") {
        numericGrade[i] = 1.25;
        }
        else
        if (letterGrade[i] == "C") {
        numericGrade[i] = 1.5;
        }

 }

    for (i = 0; i < 10; i++) {
        gpa += (numericGrade[i] * creditForCourses[i]);
    }

    gpa /= 27;

    cout << "Your GPA is: " << gpa << endl;

    break;
}
while (y=='y'||y=='Y');
cout<<"The Program will now be terminated, thank you";
getch();
}

剪切了一些代码,因为它太长了,但与第一个{}都一样,只是主题的名称不同

1 个答案:

答案 0 :(得分:1)

swith语句格式为

switch(choice) 
{
    case 1:
      //make first operation
      break;
    case 2:
    case 3:
      //make second operation
      break;
    default:
       //make else operation
}

等效于

if (choice == 1)
   //make first operation
else if (choice == 2 || choice == 3)
   //make second operation
else
   //make else operation

您的代码显然不符合开关盒的格式