c - 为什么数量大于1时我的for循环不退出?
问题描述
我已经尝试了一切来修复它。删除此代码可以修复它,但我需要它在那里。
printf("Would you like a milk with that?\n");
scanf("%s",&milk);
有人能帮我吗?这是我的学校项目。
#include <stdio.h>
#include <stdbool.h>
int main()
{
int quantity;
char milk;
double price;
int repeat = 1;
int choice;
printf("Please insert the quantity of beverage you desire\n");
scanf("%d",&quantity);
for(repeat = 1; repeat <= quantity;)
{
printf("No. Item RM\n");
printf("1. Espresso 2.10\n");
printf("2. Cappuccino 2.20\n");
printf("3. Latte 2.30\n");
printf("Please enter the beverage of your choice (1, 2 or 3)\n");
scanf("%d",&choice);
printf("Would you like a milk with that?\n");
scanf("%s",&milk);
++repeat;
}
if(choice == 1)
{
price += 2.10;
}
if(choice == 2)
{
price += 2.20;
}
if(choice == 3)
{
price += 2.30;
}
if(!(choice == 1 || choice == 2 || choice == 3 ))
{
printf("Beverage does not exist, please try again later");
return 0;
}
printf("The total price is : %f \n",price );
}
解决方案
- 你忘了初始化
price
。 }
您错误地将for
循环块的关闭放在if
语句 testing之前choice
,而它必须在它们之后,就在 final 之前printf
。- 要允许
yes
作为答案输入Would you like a milk with that?
,您应该定义char milk[4];
. 为了防止缓冲区溢出,您应该使用scanf("%3s", milk);
.
推荐阅读
- swift - 限制在 iphoneX 缺口上方的屏幕顶部
- python - Docker 和 PermissionError:[Errno 13] 权限被拒绝:'output.svg'
- java - 如何制作 TriangleWithException 对象?
- angular - 无法在 Angular 9 中设置背景图像(带渐变)
- environment - 设置环境,以便用户可以协作进行代码编辑
- bash - Jenkins管道内的bash脚本内的变量分配
- python - 无法在临时目录 Python 中创建文件
- javascript - 有没有更好的方法来检测用户的在线状态,而不是使用 setInterval 继续向服务器发送 AJAX 请求?
- c# - 如何在 C# 中为蛇游戏制作墙
- python - 在来自 Kafka 的 Spark Straming 中使用 DStream API 读取时间戳