奇怪的语句循环

时间:2017-03-28 01:07:10

标签: c function if-statement

#include<stdio.h>
#include<stdlib.h>
#include<time.h>


//prototype
void input(int *);
void statements(int, int);
void print(int, int *);




void main()
{
   int num, guess;
   time_t t;

   srand((unsigned) time(&t));
   num=rand()% 100+1;

   printf("%d\n", num);

   input(&guess);
   statements(num, guess);

}



void input(int *guess)
{
   printf("Guess a number between 1 and 100: ");
   scanf("%d", &*guess);
}

void statements (int num, int guess)
{


   if(guess==num)
      printf("You have guessed correct! The number is: %d", num);
   else if(guess>num)
   {
      printf("The number you have guessed is too big\n");
      print(num, &guess);

   }
   else if(guess<num)
   {
      printf("The number you have guessed is too small\n");
      print(num, &guess);
   }

}




    void print( int num, int *guess)
    {

        printf("Guess again: ");
        scanf("%d", &*guess);
        statements(num, guess);
    }

基本上,我正在编写一个猜谜游戏的程序作为一项任务,用户不断尝试,直到他/她的答案是正确的;但是,当我执行它时,如果用户第一次没有弄错,程序会不断告诉他数字太大了。不允许循环 例: 85 猜一个1到100:90之间的数字 你猜到的数字太大了 再猜一次:20 你猜到的数字太大了 再猜一遍:

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

除了评论中指出的问题之外,您对递归的使用是一个潜在的问题。如果用户猜测错误,你最终会搞砸掉调用堆栈。此外,指针引用的顺序,取消引用,即&*没有做任何事情,所以你应该把它拿出来。因此,使用while循环而不是使用递归的正确代码将是这样的:

void statements (int num, int guess)
{
    while (guess!=num) { 
        if(guess>num) {
            printf("The number you have guessed is too big\n");
            print(num, &guess);
        } else if(guess<num) {
            printf("The number you have guessed is too small\n");
            print(num, &guess);
        }
    }
    printf("You have guessed correct! The number is: %d\n", num);
}

void print( int num, int *guess)
{
    printf("Guess again: ");
    scanf("%d", guess);
}