C语言中的多项目价格计算
嗨,我正在尝试计算6个不同项目的总价,其中3个必须被选中。通过使用C,我尝试使用switch语句,但不幸的是,我在选择2之后卡住了。 多谢各位C语言中的多项目价格计算,c,C,嗨,我正在尝试计算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(
#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;
}
在我添加所有内容之后,一旦我启动程序,它只对第一个开关语句有效您需要一个可变的总计来添加总成本。您的代码如下所示:
#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;
}
非常感谢你们的代码,但在我添加所有东西后,一旦我启动程序,它只对第一个开关有效statement@AhmetEminKaradag,通过在scanf中的%c之前添加一个空格来修复此问题。非常感谢,我非常感激