C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确

C++ question: User think a number 1-100, program asks questions no more than 6 times to get answer. can't get correct

本文关键字:可得到 6次 不超过 答案 出问题 用户 问题 数字 程序 1-100 C++      更新时间:2023-10-16

用户必须想到一个从1到100的数字。电脑不断询问不超过6次才能得到什么用户认为数字。我不能把逻辑搞对,我不知道该怎么解决了。请有人帮帮我。

#include "std_lib_facilities.h"
// this program is not correct
// try 24 you will see it
int main()
{
cout << "Think of a number between 1 to 100n";
int max{100};
int min{0};
int answer{0};
string response{"??"};
while ((max - min) != 1)
{
cout << "Is the number < " << (max + min) / 2 << "?n";
cin >> response;
if (response == "y" || response == "yes")
{
max = ((max + min) / 2);
if ((max - min) == 1)
answer = min;
}
else if (response == "n" || response == "no")
{
min = (max + min) / 2;
if ((max - min) == 1)
answer = max;
}
else
{
error("Invalid responsen");
}
}
cout << "The answer is " << answer << endl;
keep_window_open();
return 0;
}

提前谢谢。

正如评论部分已经指出的,您的代码中至少有3个错误:

  1. 您的问题指出,用户应该想到1到100之间的数字,但变量minmax被初始化为0到100,就好像用户应该想到0到100之间。因此,应该将min初始化为1,而不是0
  2. 当用户回答"是"时;是";对于数字是否低于某个值的问题,可以将max设置为该值。这没有意义,因为您知道数字不能是这个值,但必须低于这个值。因此,应该将max设置为该值减去1
  3. min == 1max == 2时,程序询问的下一个问题是数字是否为"0"是有意义的<2〃;,以便确定该号码是CCD_ 10还是CCD_。然而,在这种情况下,您的程序会询问该数字是否为"0"<1〃;,这是没有意义的,因为它已经知道这个问题的答案是";否";。因此,与其询问数字是否小于(max + min) / 2,不如询问数字是否大于(max + min + 1) / 2

我已经清理了您的代码并修复了上面提到的错误。这是代码:

#include <iostream>
#include <string>
constexpr int MIN = 1;
constexpr int MAX = 100;
int main()
{
int min{ MIN };
int max{ MAX };
std::string response;
std::cout << "Think of a number between " << MIN << " and " << MAX << "." << std::endl;
while ( min != max )
{
int guess = (max + min + 1) / 2;
std::cout << "Is the number < " << guess << "? ";
std::cin >> response;
if ( response == "y" || response == "yes" )
{
max = guess - 1;
}
else if ( response == "n" || response == "no" )
{
min = guess;
}
else
{
std::cout << "Invalid response" << std::endl;
}
//The following line only exists for debugging purposes and can be disabled
std::cout << "min: " << min << " max: " << max << std::endl;
}
std::cout << "The number is " << min << "." << std::endl;
return 0;
}

我重新排列了代码,使数字1100只在一个地方硬编码,而不是在程序中的几个地方。这使您可以非常容易地更改范围,而无需更改程序中多个位置的数字。

我的代码没有做的一件事是在6个问题之后停止询问,因为可能需要多达7个问题才能找到正确的答案。在你的问题中,你规定它应该问不超过6次,但没有具体说明如果到那时还没有找到答案会发生什么。

相关文章: