0

谁能告诉我我的代码有什么问题。我正在尝试创建一个游戏,让计算机猜测我输入的数字。这是我的代码:


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

int main(void) {

int numberGuess = 0;
int low = 1;
int high = 100;
int computerGuess = 0;

printf("Enter a number, 1 - 100: ");
scanf("%d", &numberGuess);

while (computerGuess != numberGuess) 
{

  computerGuess = ((high - low) + low)/2;
  printf("%d ", computerGuess);

  if (numberGuess > computerGuess)
    {
    printf("Your guess was to low \n");
    low = computerGuess+1;
    }
  else if (numberGuess < computerGuess)
    {
    printf("Your guess was to high \n");
    high = computerGuess-1;
}
  else if (numberGuess == computerGuess)
{
printf("Yess!! you got it!\n");
    }
 }
return 0;
}
4

3 回答 3

2

这一行:

computerGuess = ((high - low) + low)/2;

应该:

computerGuess = (high - low)/2+low;

您正在寻找的是介于高位和低位之间的数字(这是二进制搜索,但我相信您知道这一点)。

于 2013-03-04T19:39:25.730 回答
0

修复代码:

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

int main(void) {

int numberGuess = 0;
int low = 1;
int high = 100;
int computerGuess = 0;

printf("Enter a number, 1 - 100: ");
scanf("%d", &numberGuess);

while (computerGuess != numberGuess) 
{

  computerGuess = ((high - low)/2 + low);
  printf("%d ", computerGuess);

  if (numberGuess > computerGuess)
    {
    printf("Your guess was to low \n");
    low = computerGuess+1;
    }
  else if (numberGuess < computerGuess)
    {
    printf("Your guess was to high \n");
    high = computerGuess-1;
}
  else if (numberGuess == computerGuess)
{
printf("Yess!! you got it!\n");
    }
 }

return 0; 
}
于 2013-03-04T19:43:01.233 回答
0
computerGuess = ((high - low) + low)/2;

在这里,您只需添加低,然后立即减去它,从而使代码相等

computerGuess = ((high)/2;

并且您总是比较相同的值,而 while 循环永远不会结束。

于 2013-03-04T19:38:23.893 回答