您好我正在尝试计算6种不同商品的总价,必须选择其中3种。通过使用C我尝试使用switch语句,但不幸的是我卡在2选择后。 谢谢
#include<stdio.h>
int main()
{
char ch;
int total=0;
printf("Which cou will you choose:\n");
printf("a) cpu 1 \n");
printf("b) cpu 2 \n");
scanf("%c", &ch);
switch (ch)
{
case 'a':
printf("The price is 110 \n");
total+=110;
break;
case 'b':
printf("The price is 140\n");
total+=140;
break;
default:
printf("Invalid choice.Switching to next question\n");
}
printf("Which ram will you choose:\n");
printf("q) ram 1 \n");
printf("w) ram 2 \n");
scanf("%c", &ch);
switch (ch)
{
case 'q':
printf("The price is 10 \n");
break;
case 'w':
printf("The price is 14\n");
printf("Please Wait\n");
break;
default:
printf("Invalid choice\n");
break;
}
printf("Which hdd will you choose:\n");
printf("x) hdd 1 \n");
printf("y) hdd 2 \n");
scanf("%c", &ch);
switch (ch)
{
case 'x':
printf("The price is 65 \n");
break;
case 'y':
printf("The price is 75\n");
printf("Please Wait\n");
break;
default:
printf("Invalid choice\n");
break;
}
printf("That'll cost %d",total);
return 0;
}
在我启动程序后添加所有内容后,它仅适用于第一个switch语句
答案 0 :(得分:0)
您需要一个变量total
来累计总费用。您的代码将如下所示:
#include<stdio.h>
int main()
{
char ch;
int total=0;
printf("Which option will you choose:\n");
printf("a) cpu 1 \n");
printf("b) cpu 2 \n");
scanf("%c", &ch);
switch (cpu)
{
case 'a':
printf("The price is 110 \n");
total+=110;
break;
case 'b':
printf("The price is 140\n");
total+=140;
break;
default:
printf("Invalid choice.Switching to next question\n");
}
//ask next question.
//get input
//use a switch like the above one
//add total
//repeat this as many times you want
printf("That'll cost %d",total);
return 0;
}