c - 如何在 C 中使用 switch 语句将选择添加在一起?
问题描述
我已经写出了我的大部分程序,但我必须在其中遗漏一些东西。我写了一个菜单并列出了要选择的项目,并写了一个 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");
推荐阅读
- asp.net-core - .NET Core 中的程序集绑定重定向
- r - 如何将 3 个不同表中的 3 个不同列合并为一个大列。R
- flutter - 如何在 Flutter Web 中的 Blob 和 Image 之间来回转换?
- javascript - 如何在 Jest 中仅模拟 Class 的构造函数
- sql - 总和返回正确答案......有时
- java - Java - 使用枚举捕获用户输入时出错
- javascript - 将 javascipt 数组转换为对象
- css - 悬停时缩放和变换 img
- svelte-3 - Svelte - 单击时更改导航项的样式
- javascript - 将 window.origin 与 postMessage 一起使用是否安全?