2016-03-15 73 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