用Switch语句替换if else



我正在处理下面的代码,并尝试使用switch语句而不是if/else。问题是我不知道如何让开关工作。尝试了几件事:我知道,每当一个表达式等于大小写常量时,代码就会被执行。示例:

switch (expression)  
{
case 1:
// code to be executed if 
// expression is equal to 1;
break;
}

我下面的代码有一个类似的概念,但我无法让它显示计算结果。没有错误,但它没有显示总价。

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
const int CHEESE_PIZZA = 11;
const int SPINACH_PIZZA = 13;
const int CHICKEN_PIZZA = 14;
cout << " *********** MENU ***********" << endl;
cout << setw (9) << "ITEM" << setw (20) << "PRICE" << endl;
cout << " (1) Cheese Pizza" << setw (8) << "$" 
<< CHEESE_PIZZA << endl;
cout << " (2) Spinach Pizza" << setw (7) << "$" 
<< SPINACH_PIZZA << endl;
cout << " (3) Chicken Pizza" << setw (7) << "$" 
<< CHICKEN_PIZZA << endl;
cout << endl;
cout << "What would you like? ";
int option;
cin >> option;
cout << "You picked pizza option " << option << endl;
cout << "How many orders? ";
int quantity;
cin >> quantity;
cout << "You choose quantity " << quantity << endl;
int price;
switch (option)
{
case 1:
price = CHEESE_PIZZA;
break;
case 2:
price = SPINACH_PIZZA;
break;
case 3: 
price = CHICKEN_PIZZA;
break;
default:
cout << "Please select valid item from menu. " << endl;

}
return 1;
int amount = price * quantity;
cout << "Your Bill: $ " << amount << endl;

cout << endl;

return 0;
}

我对情况4中除1、2和3之外的任何输入的输出感到困惑。

if/else语句有效:

int price;
if (option == 1) price = CHEESE_PIZZA;
else if (option == 2) price = SPINACH_PIZZA;
else if (option == 3) price = CHICKEN_PIZZA;
else {
cout << "Please select valid item from menu. " << endl;
return 1;
}

问题来自于眼球,似乎是因为您在switch语句之外return 1,这就是为什么它之后的代码永远不会运行的原因。

您应该将事例4替换为default:标签,并将return 1;移动到该事例中,同时在事例3下添加break语句。

最新更新