2016-03-15 96 views
-2

只是測試一些代碼;在我輸入'n'之前應該運行以下內容。但它在一輪後停止。任何人都可以解釋它,並幫助我實現我想要的嗎?爲什麼C中的while循環終止了

#include <stdio.h> 
int main() 
{ 
    char another = 'y'; 
    int num; 

    while (another == 'y') 
    { 
     printf ("Enter an number "); 
     scanf ("%d", &num); 
     printf ("square of %d is %d", num, num * num);   
     printf ("\nWant to enter another number y/n\n"); 
     scanf ("%c", &another); 

    } 

} 

謝謝。

我真的很感謝每一個人的評論。我在網上搜索GDB,稍後再使用它。我不得不說它使得更容易識別問題。 非常感謝。

+3

參見[這個問題](https://stackoverflow.com/questions/13542055/how-to-do-scanf-爲單焦型的-C)。 – vaindil

+3

在發佈SO之前,您是否曾想過使用您的調試器來檢查scanf讀取的內容,甚至只是爲了打印出其值? –

回答

-1

使用

scanf (" %c", &another); 
     ^^^^^ 

而且最好是寫

printf ("square of %d is %lld", num, (long long int)num * num); 
         ^^^^  ^^^^^^^^^^^^^^^^^^^^   
+0

感謝您的答案,沒有讓我覺得我什麼都不知道! – user3326293

+0

@ user3326293根本沒有。我們的初學者應該互相幫助。:) –

4

%c

scanf (" %c", &another); 

添加一個空格前面的scanf()後吃在緩衝區左外換行。


1)使用的main()

int main(void) //if no command line arguments. 

2標準清晰度)做檢查的scanf()(和其他函數的返回值),以確保沒有任何錯誤被讀出值。

+0

非常感謝。 – user3326293

+0

@ user3326293,不客氣。 :) – Haris