我总是在if
语句中使用else
switch
语句,但我决定尝试切换。我用一个开关做了基本的可乐机程序,我不能为我的生活弄清楚为什么它不起作用应该如何。当我使用数字1-5作为我的输入时,它继续给出开关默认错误消息而不是case cout语句(例如"你选择了Coke")。显然,我没有看到/
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Beverage List" << endl;
cout << "Coke = 1" << endl;
cout << "Dr. Pepper = 2" << endl;
cout << "Water = 3" << endl;
cout << "Sprite = 4" << endl;
cout << "Lemonade = 5" << endl << endl << endl;
cout << "Enter a number to choose a beverage: ";
cin >> number;
switch (number)
{
case '1':
cout << "You chose Coke";
break;
case '2':
cout << "You chose Dr. Pepper";
break;
case '3':
cout << "You chose Water";
break;
case '4':
cout << "You chose Sprite";
break;
case '5':
cout << "You chose Lemonade";
break;
default:
cout << "Error: Choice was not valid. Here is your money back.";
}
cout << "\n";
system("pause");
return 0;
}
答案 0 :(得分:2)
字符'1'
与数字1
不同。
更改
case '1':
到
case 1:
答案 1 :(得分:2)
看起来你的case语句是比较字符,而不是整数:
case '5':
请改为尝试:
case 5: