【发布时间】:2016-09-15 18:43:42
【问题描述】:
#include<stdio.h>
int main()
{
float p, r, t;
char ch = 'y';
do
{
printf("Enter principal: ");
scanf("%f", &p);
printf("Enter rate: ");
scanf("%f", &r);
printf("Enter t: ");
scanf("%f", &t);
printf("SI = %f", (p *r * t)/100 );
printf("\nCalculate SI one more time ? ('Y' for Yes, 'n' for no ) : ");
ch = getchar();
}while(ch == 'y');
return 0;
}
输出:
Enter principal: 1334
Enter rate: 4
Enter t: 2
SI = 106.720000
Calculate SI one more time ? ('Y' for Yes, 'n' for no ) :
Process returned 0 (0x0) execution time : 5.359 s
Press any key to continue.
如您所见,我无法第二次计算 SI?有什么问题?
我什至尝试用 scanf() 替换 getchar() 但它仍然无法正常工作
【问题讨论】:
-
ch = getchar();在输入缓冲区中仍有一个newline,由前一个scanf留下。 -
@WeatherVane 你能解释一下发生了什么吗?
-
大多数格式的
scanf(但不是%c)会占用 leading 空格,但会在输入缓冲区中留下任何后续内容。基于字符的输入函数,取其所有。 -
@WeatherVane 有什么解决办法
-
scanf(" %c", &ch);注意%c之前的空格,它会像其他格式说明符一样吃掉前导空格。