gpt4 book ai didi

c - 如何使用 C 中的 switch 语句将选择添加在一起?

转载 作者:行者123 更新时间:2023-11-30 16:13:00 25 4
gpt4 key购买 nike

我已经写出了我的大部分程序,但我一定遗漏了一些东西。我写了一个菜单并列出了要选择的项目,并写了一个 switch 语句来运行选择。我如何才能将选项加在一起得出总数?现在它要求两个选择(稍后将其更改为 3),并且在输入两个选择后仅运行第一个选择的金额。不知道出了什么问题。

printf("1. Hamburger        $%.2lf \n", Hamburger_Price);
printf("2. Cheeseburger $%.2lf \n", Cheeseburger_Price);
printf("3. Chicken Sandwich $%.2lf \n", Chicken_Sandwich_Price);
printf("4. Fries $%.2lf \n", Fries_Price);
printf("5. Onion Rings $%.2lf \n", Onion_Rings_Price);
printf("6. Soda $%.2lf \n", Soda_Price);
printf("7. Milkshake $%.2lf \n", Milkshake_Price);
printf("8. Exit\n\n");

printf("Please make a selection: ");
scanf("%i", &selection);


switch(selection)
{
case 1:
totalprice += Hamburger_Price;
break;

case 2:
totalprice += Cheeseburger_Price;
break;

case 3:
totalprice += Chicken_Sandwich_Price;
break;

case 4:
totalprice += Fries_Price;
break;

case 5:
totalprice += Onion_Rings_Price;
break;

case 6:
totalprice += Soda_Price;
break;

case 7:
totalprice += Milkshake_Price;
break;

case 8:
printf("Thank you for your order. \n");
break;

default:
printf("Sorry we dont have that. \n");
}

printf("Please make another selection: ");
scanf("%i", &selection);


printf("Your total comes to $%.2lf \n\n", totalprice);

最佳答案

Switch 语句不是循环语句,它只执行一次。为了多次进入 switch 语句,可以将其放在循环语句中。并且不要忘记添加退出条件。例如,假设结束条件是引入值 8:

printf("Please make a selection: ");
scanf("%i", &selection);

while(selection != 8)
{
switch(selection)
{
/*your code*/
}
printf("Please make another selection: ");
scanf("%i", &selection)
}
/*I think there is no need for the "case 8:" in your code*/
printf("Thank you for your order. \n");

关于c - 如何使用 C 中的 switch 语句将选择添加在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58194374/

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