为什么该程序卡住了?

时间:2020-09-03 18:35:26

标签: c

我正在编写一个小的玩具程序,可以猜测用户选择的数字,但是当我运行它时,它会卡在其中:

Is your number higher or lower? (h/l): 

这是我到目前为止编写的代码:

#include <stdio.h>
#include <stdlib.h> // includes srand() and rand()
#include <time.h>

#define MAX 100
#define MIN 1

int main(void)
{
  time_t t;
  char response;
  int lower = MIN, higher = MAX, guess;

  srand(time(&t)); //Initializes random number generator
  guess = (random() % 100) + 1; // Initial guess

  printf("Pick a number from 1 to 100. I'll try to guess it.\n");
  printf("Is your number %d? (y/n): ", guess);
  while ((response = getchar()) != 'y')
  {
    printf("Is your number higher or lower? (h/l): ");
    
    while ((response = getchar()) == 'h' || response == 'l')
    {
      if (response == 'h') {
        lower = guess;
        guess = (higher - guess) / 2;
        printf("Is it %d?: ", guess);
      } else if (response == 'l'){
        higher = guess;
        guess = (higher - guess) / 2;
        printf("Is it %d?: ", guess);
      }
    }
  }
  printf("Great!!\n");

  return 0;
}

由于某种原因,它没有进入第二个循环,在该循环中,我检查response等于h还是l

1 个答案:

答案 0 :(得分:1)

好吧,我找到了一种处理换行符的方法,并且仍然可以使用getchar()来获取输入:

#include <stdio.h>
#include <stdlib.h> // includes srand() and rand()
#include <time.h>

#define MAX 100
#define MIN 1

char get1stChar(void);

int main(void)
{
  time_t t;
  char response;
  int lower = MIN, higher = MAX, guess;

  srand(time(&t)); //Initializes random number generator
  guess = (random() % 100) + 1; // Initial guess

  printf("Pick a number from 1 to 100. I'll try to guess it.\n");
  printf("Is your number %d? (y/n)\n"
     "Or is it Higher or Lower (h/l): ", guess);
  response = get1stChar();

  while (response != 'y')
  {
    printf("you're here\n");
    while (response == 'h' || response == 'l')
    {
      if (response == 'h') {
        lower = guess;
        guess = (higher - lower) / 2;
        printf("Higher: %d, Lower: %d\n", higher, lower);
        printf("Is it %d, higher or lower (y/h/l)?: ", guess);
      } else if (response == 'l'){
        higher = guess;
        guess = (higher - lower) / 2;
        printf("Higher: %d, Lower: %d\n", higher, lower);
        printf("Is it %d, higher or lower (y/h/l)?: ", guess);
      } 
      response = get1stChar();
    }
  }
  printf("Great!!\n");

  return 0;
}

char get1stChar(void)
{
  char ch;

  ch = getchar();
  while ((getchar()) != '\n');

  return ch;
}