c - 为什么循环没有停止?
问题描述
#include <stdio.h>
#include <stdlib.h>
#define NEWGEAR 15.0
#define USEDGEAR 5.0
int main() {
int type;
int num_items;
float total;
printf("Welcome to the market\n");
printf("What would you like to do\n");
printf("\t1-Buy New Gear\n");
printf("\t2-Buy used gear\n");
printf("\t3-Quit\n");
scanf("%d", &type);
while (type != 3) {
switch (type) {
case 1:
printf("How many new items would you like?\n");
scanf("%d", &num_items);
total = num_items * 15.0;
break;
这是代码不断询问您想要多少新项目的地方?
case 2:
printf("How many old items would you like?\n");
scanf("%d", &num_items);
total = num_items * USEDGEAR;
break;
这是代码不断询问您想要多少旧物品的地方?案例3:中断;
default:
printf("Not a valid option\n");
break;
}
}
printf("Your total cost is %f\n",total);
return 0;
}
我的两个选择都在循环
解决方案
您的循环逻辑有缺陷:
- 您应该在循环内移动提示代码。
- 您应该更新
total
每个答案。 - 您应该测试
scanf()
转换用户输入是否成功。
这是修改后的版本:
#include <stdio.h>
#define NEWGEAR 15.0
#define USEDGEAR 5.0
int main() {
int type;
int num_items;
double total = 0;
printf("Welcome to the market\n");
for (;;) {
printf("What would you like to do\n");
printf("\t1-Buy New Gear\n");
printf("\t2-Buy used gear\n");
printf("\t3-Quit\n");
if (scanf("%d", &type) != 1 || type == 3)
break;
switch (type) {
case 1:
printf("How many new items would you like?\n");
if (scanf("%d", &num_items) == 1)
total += num_items * 15.0;
break;
case 2:
printf("How many old items would you like?\n");
if (scanf("%d", &num_items) == 1)
total += num_items * USEDGEAR;
break;
default:
printf("Not a valid option\n");
break;
}
}
printf("Your total cost is %f\n", total);
return 0;
}
推荐阅读
- c - 了解“alignas”和 ubsan 的效果
- linux - 为 curl 转义分号、双引号和反斜杠
- angular - Angular CDK 模态对话框的 Jasmine 规范失败
- java - 在 Race Program 中,当它与终点线碰撞时似乎无法宣布获胜者-java
- asp.net - Get Count of IList / ICollection property group by date | Entity Framework Core
- python - How to make ''string in list'' case-insensitive in python3.8.3
- google-sheets - 如何通过仅在第一个单元格中写入公式来填充整个列
- wordpress-gutenberg - Gutenberg/WordPress - Open sidebar by default
- bash - Batch rename all files in a directory to basename-sequentialnumber.extention
- docker - 在 docker 中运行的红隼无法提供静态内容