【发布时间】: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