0

尽管提供了 'n' 作为输入,该程序仍会进入无限循环以退出 while 循环。可能是什么问题 ?

#include<stdio.h>
    main()
    {        
  int num,p=0,q=0,r=0;
    char check='y';

   while(check!='n')
     {
   printf("do you want to enter a number y or n");
    scanf("%c",&check);
    getchar();
    printf("enter a number");
     scanf("%d",&num);


    if(num>0)
      p++;
       else if(num<0)
      q++;
     else 
     r++;


    }
     printf("positive=%d\t negative=%d\t zero=%d\t",p,q,r);
        }
4

3 回答 3

1

问题是在循环while顶部重新评估条件之前,循环不会退出。我建议将你的循环改造成这样的东西。

// we've purposely changed this to an infinite loop because
// we hop out on condition later
while(1)
{
    printf("do you want to enter a number y or n");
    scanf("%c",&check);
    getchar();

    // here's the code that will jump out of the loop early if the user
    // entered 'n'
    if('n' == check)
        break;

    // user didn't enter 'n'...they must want to enter a number
    printf("enter a number");
    scanf("%d",&num);

    if(num>0)
        p++;
    else if(num<0)
        q++;
    else 
        r++;
}
于 2013-01-30T16:41:51.583 回答
1
while(check!='n')
{
    printf("do you want to enter a number y or n");
    scanf("%c",&check);
    getchar();
    printf("enter a number");
    scanf("%d",&num);

scanf("%d", &num);换行符留在输入缓冲区中,因此在循环的下一次迭代中,存储在check. 之后,将getchar()消耗您输入的'n'或。'y'然后scanf("%d", &num);跳过缓冲区中留下的换行符,扫描输入的数字,并将换行符留在缓冲区中。您需要在扫描数字和查询是否需要下一次迭代之间删除换行符。

除此之外,最好在用户输入后立即退出循环'n',所以

while(check!='n')
{
    printf("do you want to enter a number y or n");
    scanf("%c",&check);
    if (check == 'n') {
        break;
    }
    printf("enter a number");
    scanf("%d",&num);
    getchar();  // consume newline

会更好。如果用户输入不符合预期,这仍然会带来坏事,所以如果你想要一个健壮的程序,你需要检查返回值scanf以知道转换是否成功,并在扫描前后完全清空输入缓冲区在号码中。

于 2013-01-30T16:53:49.293 回答
0

您没有检查字符输入。应该是这样的:

printf("do you want to enter a number y or n");
scanf("%c",&check);
/* This is what you need to add */
if (check == 'y') {
  getchar();
  printf("enter a number");
  scanf("%d",&num);
}
于 2013-01-30T16:41:13.200 回答