【问题标题】:Using a switch within a loop in c在 c 中的循环中使用开关
【发布时间】:2022-11-25 03:45:19
【问题描述】:

我有一个开关,我想将其嵌套在一个循环中,该循环由从用户收到的变量进行计数器控制。但是,当我将用户值放入循环中时,它会在 1 次迭代后退出。当我在 for 循环的标题中手动放置一个整数值时,它工作得很好......是导致错误的变量计数吗?

这是我的代码:




int main()
{
    int i = 0, cost, count, tennis = 18000, Badminton = 14000, Swimming = 16000,
        total_cost = 0;

    int swim_count = 0, tennis_count = 0, Badminton_count = 0;

    char sports_event, name[30];

    printf("How many persons are in your party: ");

    scanf("%d", &count);

    for (i = 0; i < count; i++)
    {
        printf("\nEnter customer name: ");

        scanf("%s", name);

        printf(
            "\nWhat event would you like to partake in?"

            "\n'T' FOR Tennis 'B' for Badminton and 'S' for Swimming: ");

        scanf("%c", &sports_event);

        switch (sports_event)
        {
            case 'T':
                cost = 18000,

                total_cost = total_cost + tennis;

                tennis_count = tennis_count + 1;

                printf("\nCustomer name: %s", name);
                printf("\nEvent type: Tennis");
                printf("\nThe even cost is $%d\n", cost);

                break;

            case 'B':
                cost = 14000;

                total_cost = total_cost + Badminton;

                Badminton_count = Badminton_count + 1;

                printf("\nCustomer name: %s", name);
                printf("\nEvent type: Badminton");
                printf("\nThe even cost is $%d\n", cost);

                break;

            case 'S':
                cost = 16000;

                total_cost = total_cost + Swimming;

                swim_count = swim_count + 1;

                printf("\n Customer name: %s", name);
                printf("\n Event type: Swimming");
                printf("\n The even cost is $%d\n", cost);

                break;

            default:

                printf("SPORTS EVENT IS INVALID... PLEASE TRY AGAIN\n");
        }
    }

    return 0;
}

【问题讨论】:

  • 在对您的代码应用基本格式后,很明显它是不完整的。请发布编译的Minimal, Reproducible Example,或者以其他方式产生您需要帮助才能理解的明确警告/错误。
  • for (i = 0; i &lt;= count; i++) 将迭代count + 1 次。
  • scanf("%s", &amp;sports_event); 尝试将 string 读入单个 char。至少,使用scanf(" %c", &amp;sports_event); 来读取单个字符。注意 consume optional whitespace 的前导空格。考虑使用 fgets 来处理输入行。

标签: c loops switch-statement


【解决方案1】:

我会建议: 对于 (i = 0; i < count; i++)

(注意'<',不是'<=')

在您当前的实施中,您总是必须输入比您预期少一个的聚会人数。即输入 0 会给你一次迭代。 1会给你2等等。

除此之外,它工作得很好。 除非我不明白这个问题。

【讨论】:

    猜你喜欢
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多