请问这里的printf为什么会输出两遍,应该如何解决?
课程设计
1
#include<stdio.h>
#define a0 2.05
#define b0 1.15
#define c0 1.09
int main(void)
{
double pound=0;
double sum=0;
double price=0;
char ch='0';
while(ch!='q'){
printf("which are you want?\n");
scanf("%c",&ch);
switch(ch)
{
case 'a':
printf("how much you want?\n");
scanf("%lf",£);
price=price+pound*a0;
sum=sum+pound;
break;
case 'b':
printf("how much you want?\n");
scanf("%lf",£);
price=price+pound*b0;
sum=sum+pound;
break;
case 'c':
printf("how much you want?\n");
scanf("%lf",£);
price=price+pound*c0;
sum=sum+pound;
break;
default: break;
}
}
if(sum<5){
price=price+6.5;
}else if(sum>5&&sum<20){
price=price+14;
}else{
price=price+(0.5*(sum-20)+14);
}
if(price>100){
price=price*0.95;
}
printf("%lf %lf",sum,price);
return 0;
}
运行结果及报错内容
-
你输入a并回车时,实际上是输入a\n,最后一个scanf里多出的\n会传给开头的scanf。 有很多解决方法,如: 1.35行和36行间插入getchar(); 接收\n 2.13行改成scanf("\n%c",&ch); 3.13行改成do{ scanf("%c", &ch); } while (ch == '\n');
-
每个 scanf("%lf",£);后面加一句getchar(),接收掉输入浮点数后的换行符。否则下次循环时 scanf("%c",&ch);自动接收换行符,从而出现连续两次提示输入的现象
发表回复