这个程序检查输入数据是否有效和多个输入之间的衔接比较费劲
虽然用了两个goto,不过似乎还是比较容易看明白
#include <stdio.h>
int sushu(int a);
int main(void)
{
char i;
int zhekou;
float totalcost,aftercost,n,transfee,a_num,b_num,c_num,totalweight;
while(1)//大循环,直到按e退出
{
a_num=0,b_num=0,c_num=0,zhekou=0;
while(1)//多轮选购
{
printf("请选购蔬菜:\n");
printf("a)洋蓟 b)甜菜 c)胡萝卜 d)选好了 e)不买了\n");
while(1)//确保输入的品种选项有效
{
if ((i=getchar())=='\n') i=getchar();
while(getchar()!='\n');
switch(i)
{
case 'a': break;
case 'b': break;
case 'c': break;
case 'd': goto smallend;
case 'e': goto end;
default: printf("请输入正确的字母:\n");
continue;
}
break;
}
//确保输入的磅数有效
printf("请输入磅数:\n");
while(scanf("%f",&n)!=1)
{
printf("请输入正确的磅数:\n");
while(getchar()!='\n');
}
while(getchar()!='\n');
switch(i)
{
case 'a': a_num+=n;
break;
case 'b': b_num+=n;
break;
case 'c': c_num+=n;
break;
}
}
smallend:
//总计金额
totalweight=a_num+b_num+c_num;
totalcost=2.05*a_num+1.15*b_num+1.09*c_num;
if (totalcost>=100.00)
{aftercost=totalcost*95.0/100.0;
zhekou=1;}
//运费
if (totalweight==0) transfee=0;
else if(totalweight<=5) transfee=6.5;
else if (totalweight<=20) transfee=14;
else transfee=14+(n-20)*0.5;
printf("您购买了洋蓟%.2f磅,共%.2f元。\n",a_num,a_num*2.05);
printf("您购买了甜菜%.2f磅,共%.2f元。\n",b_num,b_num*1.15);
printf("您购买了胡萝卜%.2f磅,共%.2f元。\n",c_num,c_num*1.09);
printf("总共需要%.2f元。\n",totalcost);
if (zhekou==1)printf("有%%5折扣,折后价格为%.2f元。\n",aftercost);
else printf("无折扣,总价为%.2f元。\n",totalcost);
printf("运费为%.2f元。\n",transfee);
printf("总费用为%.2f元。\n",(zhekou==1?aftercost:totalcost)+transfee);
}
end:printf("谢谢光临!\n");
return 0;
}