计算机猜猜我的编号C编程

时间:2013-03-04 19:33:10

标签: c

任何人都可以告诉我我的代码有什么问题。我正在尝试创建一个计算机猜测我输入的数字的游戏。这是我的代码:


#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;
}

3 个答案:

答案 0 :(得分:2)

这一行:

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

应该是:

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

你要找的是你的高低之间的数字(这是二分搜索,但我相信你知道的。)

答案 1 :(得分:0)

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

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

computerGuess = ((high)/2;

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

答案 2 :(得分: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; 
}