首页 > 解决方案 > 为什么数量大于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 ); 
}

标签: c

解决方案


  • 你忘了初始化price
  • }您错误地将for循环块的关闭放在if语句 testing之前choice,而它必须在它们之后,就在 final 之前printf
  • 要允许yes作为答案输入Would you like a milk with that?,您应该定义char milk[4];. 为了防止缓冲区溢出,您应该使用scanf("%3s", milk);.

推荐阅读