大家好,我创建了这个程序来计算折扣后客户必须支付的净额。 它计算磨布或手摇织机商品的折扣。我尝试使用 goto 创建一个循环,当您输入既不是手织机也不是磨布的选择时,该循环就会终止,但它仅在一次迭代后就终止。如何使用 goto 创建一个循环,该循环仅在我输入错误的字母表时才会终止?
// a clothes showroom has announced a discount on mill cloth and handloom items , wap using switch and if //stmts to compute the net amount to be paid by customer
#include<stdio.h>
float netmillcloth(float a)
{
if(a>300)
a-=0.10*a;
else if(a>200)
a-=0.075*a;
else if(a>100)
a-=0.05*a;
return a;
}
float nethandloom(float a)
{
if(a>300)
a-=0.15*a;
else if(a>200)
a-=0.10*a;
else if(a>100)
a-=0.075*a;
else
a-=0.05*a;
return a;
}
int main()
{
char item;
float purchase_amt, net; // net is amount to be paid after discount
input:
printf("Enter the type of item bought\nM for millcloth\nH for handllom items\nother key to end program\n");
scanf("%c",&item);
switch(item)
{
case 'M':
case 'm':
printf("\nenter purchase amount:");
scanf("%f",&purchase_amt);
net=netmillcloth(purchase_amt);
break;
case 'H':
case 'h':
printf("\nenter purchase amount:");
scanf("%f",&purchase_amt);
net=nethandloom(purchase_amt);
break;
default:
goto stop;
}
printf("\nThe final amount to be paid is:%f\n\n",net);
goto input;
stop:
printf("\nEnd of program");
}
我使用了 goto 语句,但它没有导致循环
这是因为
scanf
将 '\n'
留在缓冲区中,因此第二个循环读取它,然后 switch
转到 default:
读取字符串清理缓冲区。
int main()
{
char item[10];
float purchase_amt, net; // net is amount to be paid after discount
input:
printf("Enter the type of item bought\nM for millcloth\nH for handllom items\nother key to end program\n");
fgets(input, sizeof(input), stdin);
switch(item[0])
{
/* ... */