gpt4 book ai didi

c++ - 为什么我的 switch case 被跳过并打印 default ?

转载 作者:太空宇宙 更新时间:2023-11-04 14:37:57 24 4
gpt4 key购买 nike

我编写此 C++ 代码是为了模拟自动售货机。每当输入用户的选择时,数字 1-5 在 switch 语句中各分配一个 case,所有 case 都不会执行:程序无法识别有效输入,只会打印出 default case 语句。为什么会这样?

#include <iostream>

using namespace std;

int main()
{
int choice;
double dollars;

cout << "==============================================================\n";
cout << "* *\n";
cout << "* VENDING MACHINE SIMULATOR *\n";
cout << "* *\n";
cout << "==============================================================\n";

cout << "Your Choices Are:\n";

cout << "1) Coke - $1.75\n";
cout << "2) Pepsi - $2.25\n";
cout << "3) Sprite - $1.25\n";
cout << "4) 7-up - $1.15\n";
cout << "5) Water - $2.20\n";

// Ask for user's selection.

cout << "What would you like to purchase today?\n";
cin >> choice;
switch (choice)
{
case '1':
{
cout << "How many dollar bills will you use?\n";
cin >> dollars;
{
if (dollars > 1.75)
{
cout << "You purchased: Coke\n";
cout << "Your change is: $"<< (dollars - 1.75);
}
else
{
cout << "You do not have enough money for this purchase. Goodbye!\n";
}
}
}
break;
case '2':
{
cout << "How many dollar bills will you use?\n";
cin >> dollars;
{
if (dollars > 2.25)
{
cout << "You purchased: Pepsi\n";
cout << "Your change is: $"<< (dollars - 1.75);
}
else
{
cout << "You do not have enough money for this purchase. Goodbye!\n";
}
}
}
case '3':
{
cout << "How many dollar bills will you use?\n";
cin >> dollars;
{
if (dollars > 1.25)
{
cout << "You purchased: Sprite\n";
cout << "Your change is: $"<< (dollars - 1.25);
}
else
{
cout << "You do not have enough money for this purchase. Goodbye!\n";
}
}
}
break;
case '4':
{
cout << "How many dollar bills will you use?\n";
cin >> dollars;
{
if (dollars > 1.15)
{
cout << "You purchased: 7-up\n";
cout << "Your change is: $"<< (dollars - 1.15);
}
else
{
cout << "You do not have enough money for this purchase. Goodbye!\n";
}
}
}
break;
case '5':
{
cout << "How many dollar bills will you use?\n";
cin >> dollars;
{
if (dollars > 2.20)
{
cout << "You purchased: Water\n";
cout << "Your change is: $"<< (dollars - 2.20);
}
else
{
cout << "You do not have enough money for this purchase. Goodbye!\n";
}
}
}

break;
default: cout << "Your choice is INVALID. Goodbye!\n";
}
return 0;
}

最佳答案

删除 case 语句中使用的单引号。

改变

 case '1':

case 1: 

其他人也一样。

'1' 是字符常量,而 1 是整数常量。当使用 ASCII 编码时,'1' 的计算结果为数字 49,这显然不等于数字 1。因此,当您输入 1 作为输入时,case: 分支不会执行。

关于c++ - 为什么我的 switch case 被跳过并打印 default ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com