gpt4 book ai didi

C++ 猜谜游戏 : unable to get midpoint properly

转载 作者:太空狗 更新时间:2023-10-29 22:56:59 27 4
gpt4 key购买 nike

我在做一个示例练习时遇到了一些麻烦。

目标是让计算机通过反复取中点直到达到数字来猜测您的数字。我拥有一切,除了我似乎无法“降低”工作。

#include <iostream>
using namespace std;

void playOneGame();
bool shouldPlayAgain();
int getAverage(int min, int max);
int getLow(int min, int max);
int getHigh(int min, int max);
char getResponse();

const int MAX_VALUE = 100;
const int MIN_VALUE = 0;
int AVERAGE = 50;
char choice;
int high = MAX_VALUE;
int low = MIN_VALUE;

int main()
{
do
{
playOneGame();
} while (shouldPlayAgain());

return 0;
}

void playOneGame()
{
cout<<"Think of a number between " << MIN_VALUE << " and " << MAX_VALUE << endl;
getAverage(MIN_VALUE, MAX_VALUE);
}

int getAverage(int min, int max)
{
AVERAGE = (max - min)/2;
getResponse();
}

int getHigh(int low, int max)
{
low = AVERAGE;
AVERAGE += ( high - low ) / 2;
getResponse();
}

int getLow(int low, int max)
{
high = AVERAGE;
AVERAGE -= (high - low) /2;
getResponse();
}

char getResponse()
{
cout << "Is it " << AVERAGE << " ?" << " (h/l/c): " << endl;
cin >> choice;
if(choice == 'h' || choice == 'H')
{
getHigh(low, high);
}
else if(choice == 'l' || choice == 'L')
{
getLow(low, high);
}
else
{
cout<< "Got it!" <<endl;
}
}

bool shouldPlayAgain()
{
bool status;
char choice;

cout << "Do you want to play again? Y/N\n";
cin >> choice;

if(choice == 'y' || choice == 'Y')
status = true;
else
status = false;

return status;
}

#15 的示例输出如下:

Think of a number between 0 and 100Is it 50 ?  (h/l/c):  lIs it 25 ?  (h/l/c):  lIs it 13 ?  (h/l/c):  hIs it 19 ?  (h/l/c):  lIs it 10 ?  (h/l/c):  hIs it 14 ?  (h/l/c):  hIs it 16 ?  (h/l/c):  lIs it 8 ?  (h/l/c):  hIs it 12 ?  (h/l/c):  hIs it 14 ?  (h/l/c):  hIs it 15 ?  (h/l/c):  cGot it!Do you want to play again? Y/N

代替

Is it 25 ?  (h/l/c):  lIs it 13 ?  (h/l/c):  hIs it 19 ?  (h/l/c):  lIs it 10 ?  (h/l/c): 

应该是:

Is it 25 ?  (h/l/c):  lIs it 13 ?  (h/l/c):  hIs it 19 ?  (h/l/c):  lIs it 16 ?  (h/l/c): 

最佳答案

您的变量作用域有问题。

此处的变量“low”具有局部作用域。它使用传递给函数的值

int getHigh(int low, int max)
{
low = AVERAGE;

赋值给low意味着赋给局部变量,而不是全局变量

此处的变量“high”具有全局范围。它使用此页面上任何位置分配的值

int getLow(int low, int max)
{
high = AVERAGE;
AVERAGE -= (high - low) /2;

另外,尝试使用函数的返回值。

关于C++ 猜谜游戏 : unable to get midpoint properly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46272808/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com