2016-09-15 28 views
0
#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; 

} 

輸出:C:無法接收使用輸入scanf()的

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

'ch = getchar();'還有一個'newline'仍在輸入緩衝區中,由前一個'scanf'留下。 –

+0

@WeatherVane你會解釋發生了什麼事嗎? – Cody

+0

帶有大多數格式(但不是'%c')的'scanf'會消耗*領先*空格,但會在輸入緩衝區中留下任何後續內容。基於字符的輸入函數完全取決於那裏。 –

回答

1

scanf停止讀取。

所以最後你scanf(對於t)停止閱讀只是RET之前,你鍵入T的值之後,按下。 getchar()然後讀取下一個字符,這是一個'\n'RET),並且不等於'y',因此它結束。

你不應該混合使用多種輸入法;如果使用scanf,請保留scanf,並讓它讀取一個字符(scanf(" %c",&ch);)或其他解決方案;或者在scanf之後加上getchar()並閱讀'\n'並忽略它。