C:无法使用scanf()接收输入

时间:2016-09-15 18:43:43

标签: c scanf

#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(),但它仍无法正常工作

1 个答案:

答案 0 :(得分:1)

scanf在数字完成时停止读取(在第一个不能作为其一部分的字符处)。

因此,在键入t的值之后按下的 RET 之前,scanf(对于t)的最后一个停止getchar()然后读取下一个字符,即'\n' RET ),这不等于'y',所以它结束。

你不应该混合多种输入法;如果你使用scanf,请留在scanf,并让它读取一个字符(scanf(" %c",&ch);)或其他一些解决方案;或者在'\n'之后使用额外getchar()阅读scanf并忽略它。