C猜测游戏上下限

时间:2014-01-31 03:25:19

标签: c

好的,所以这个程序要求用户输入下限和上限,对象是程序根据反馈系统猜测数字(-1,0,1)。一切都有效,并且每当我给它反馈时它就会编译,它会加倍一个数字,例如输出。任何帮助将非常感激,因为我仍然学习总是开放的建议感谢

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

int main(void) {

int low;
int high;
int Guess;
int feedback;


printf("Enter Upper bound number: ");
scanf("%d", &high);

printf("Enter lower bound number: ");
scanf("%d", &low);

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


while (feedback != 0) 
{

printf("my guess is: %d ", Guess);

printf("What do you think?");
scanf("%d", &feedback);

//guess was too low 
if (feedback == -1)
{
Guess = Guess+1; 
printf("my guess is: %d ", Guess);

printf("What do you think?");
scanf("%d", &feedback);
}

//guess was too high
else if (feedback == 1)
{
Guess = Guess-1; 
printf("my guess is: %d ", Guess);

printf("What do you think?");
scanf("%d", &feedback);
}

 else if (feedback == 0)
{
printf("I win!\n");
}
}

return 0;
}

输出:

Enter a upper bound number: 40
Enter a lower bound number: 20
my guess is: 30 what do you think? -1
my guess is: 31 what do you think? -1
my guess is: 31 what do you think? -1
my guess is: 32 what do you think? -1
my guess is: 32 what do you think? -1
my guess is: 33 what do you think? -1
my guess is: 33 what do you think? -1
my guess is: 34 what do you think? -1
my guess is: 34 what do you think? -1
my guess is: 35 what do you think? 0
I win!

4 个答案:

答案 0 :(得分:1)

建议的更改以在每次猜测后将剩余范围平分。

// Initialize
int feedback = !0;  // @Digital_Reality

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

//guess was too low 
if (feedback == -1) {
  // Guess = Guess+1; 
  low = Guess+1;
  Guess = (high + low)/2;
  ....

//guess was too high
else if (feedback == 1) {
  // Guess = Guess-1; 
  high = Guess-1;
  Guess = (high + low)/2;
  ....

答案 1 :(得分:1)

printfs之前取走while loop.无论如何,你有if

内的人
printf("my guess is: %d ", Guess);
printf("What do you think?");
scanf("%d", &feedback);
while (feedback != 0) 
{
    //guess was too low 
    if (feedback == -1)
    {

PS:使用feedback或其他+号码初始化1

答案 2 :(得分:0)

Chux是正确的。如果您不希望程序重复,那么您只需在if语句中取出printf和scanf,或将while循环中的print / scanf带到外面。

答案 3 :(得分:0)

由于你的循环,你得到双倍输出。您正在测试输入,然后在'if'中打印您的猜测并再次接受输入。收到输入后,循环重新启动并打印当前的猜测值并请求输入。在你的'if'中,只需更改guess的值,让循环继续而不是提示。