首页 > 解决方案 > 电脑猜你的号码

问题描述

我需要制作一个“猜谜游戏”,但我被困住了,因为我不确定这是否是正确的制作方法,因为在玩游戏时很难找到我正在考虑的数字。

#include <iostream>
#include <string>
using namespace std;
int main ()
{
int guess;
int n=500;
cout<<"Think of a number from 1 to 1000."<<endl;
cout<<"The number is : 1. 500"<<endl;
cout<<"2. Bigger than 500"<<endl;
cout<<"3. Smaller than 500"<<endl;
cin>>guess;

while(n<=2000)
{
    if(guess==1)
    {
        cout<<"The computer has guessed the number!";
        break;
    }
    else if(guess==2)
    {
        n+=n/2;
        cout<<"The number is :\n1."<<n<<endl;
        cout<<"2. Bigger than "<<n<<endl;
        cout<<"3. Smaller than "<<n<<endl;
        cin>>guess;
    }
    else if(guess==3)
    {
        n-=n/2;
        cout<<"The number is :\n1."<<n<<endl;
        cout<<"2. Bigger than "<<n<<endl;
        cout<<"3. Smaller than "<<n<<endl;
        cin>>guess;
    }
  }
}

我似乎找不到更好的方法来制作游戏。这个数字总是超过,1000所以我不得不将它设置while为低于2000它才能工作。

如果我可以设置n+=n/2公式以便拆分作为n变量的最后一个数字,那就太好了。例如 : 500+(500/2), then 750+(250/2), then 875+(125/2)(不确定当125拆分为时它会如何继续62.5)或与n-=n/2.

标签: c++

解决方案


#include <iostream>
using namespace std;

int main()
{
    int guess;
    int min = 0, current = 500, max = 1000;
    cout << "Think of a number from 1 to 1000." << endl;
    cout << "The number is : 1. 500" << endl;
    cout << "2. Bigger than 500" << endl;
    cout << "3. Smaller than 500" << endl;
    cin >> guess;
    while (current <= 2000)
    {
        if (guess == 1)
        {
            cout << "The computer has guessed the number!";
            break;
        }
        else if (guess == 2)
        {
            min = current;
            current = (min + max) / 2;

            cout << "The number is :\n." << current << endl;
            cout << "2. Bigger than " << current << endl;
            cout << "3. Smaller than " << current << endl;
            cin >> guess;
        }
        else if (guess == 3)
        {
            max = current;
            current = (min + max) / 2;
            cout << "The number is :\n." << current << endl;
            cout << "2. Bigger than " << current << endl;
            cout << "3. Smaller than " << current << endl;
            cin >> guess;
        }
    }
}

这应该有效。并在每次猜测后有效地限制域minmax


推荐阅读