【问题标题】:Question on Purchasing which involves a while and switch statement采购问题涉及while和switch语句
【发布时间】:2021-04-29 17:23:19
【问题描述】:

代码基本上是询问每种不同颜色的袋子的总成本,我希望退出 while 循环并打印和计算总成本。但是我遇到了一个并发症,它在某种程度上有效,但我希望它一直循环,直到输入“6”,所以它可以总计,但它根本没有。我想知道如何让它循环主要问题并退出加总。它会循环问题,它可以退出但总数等于垃圾数字。

#include <stdio.h>
#include <stdlib.h> 

int main()
{
    int total, price, bags, colour, cost, Exit ;
    
    printf ("********************************************\n Enter 6 to exit if you desire to do so\n");
    printf ("********************************************\nEnter the colour you desire:\n 1)Black\n 2)Red\n 3)Yellow\n 4)Green\n 5)Other\n********************************************\n");
    scanf("%d", &colour);
    while (Exit!=6)
    {
        switch (colour)
        {
            case 1:
            {
                printf("Enter the number of bags you intend:  ");
                scanf("%d", &bags);
                price=400;
                cost=cost+(price*bags);
            }
            break;
            case 2:
            {
                printf("Enter the number of bags you intend:  ");
                scanf("%d", &bags);
                price=350;
                cost=price*bags;
            }
            break;
            case 3:
            {
                printf("Enter the number of bags you intend:  ");
                scanf("%d", &bags);
                price=120;
                cost=cost+(price*bags);
            }
            break;
            case 4:
            {
                printf("Enter the number of bags you intend:  ");
                scanf("%d", &bags);
                price=200;
                cost=cost+(price*bags);
            }
            break;
            case 5:
            {
                printf("Enter the number of bags you intend:  ");
                scanf("%d", &bags);
                price=50;
                cost=cost+(price*bags);
            }
            break;
            
        }
        printf("********************************************\n Are you complete with your purchase? If so enter 6\n");
        scanf("%d", &Exit);
    }
   
    printf("The total is %d", total=total+cost);
    return 0;
}

【问题讨论】:

  • 您在多个地方有未定义的行为。 total=total+cost 是其中之一,因为 total 未初始化。

标签: c while-loop switch-statement


【解决方案1】:

确保首先将总计和成本初始化为零。如前所述,您当前的设置会导致未定义的行为。这是一个解决方案:

int total = 0, price, bags, colour, cost = 0, Exit = 0;

【讨论】:

    【解决方案2】:

    很难理解你在问什么,但如果我理解正确,你想循环直到输入 6。

    1. 所有变量都是未初始化的,因此它们包含未定义的值。在声明后将它们初始化为适当的值。您的问题在于变量总和成本,因为它们一开始就包含垃圾值。

    2 至于案例 2 的小错误,您缺少右侧的成本。

    1. 您实际上并不需要 var total,因为您的总成本等于按成本持有的价值。打印出来。

    您遇到的大部分问题都是由第 1 点引起的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      相关资源
      最近更新 更多