首页 > 解决方案 > 为什么循环没有停止?

问题描述

#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;
}

我的两个选择都在循环

标签: cloops

解决方案


您的循环逻辑有缺陷:

  • 您应该在循环内移动提示代码。
  • 您应该更新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;
}

推荐阅读