数字猜谜游戏与不合逻辑的错误

Number guessing game with illogical bug

本文关键字:不合逻辑 错误 游戏 数字      更新时间:2023-10-16
#include <iostream>
#include <cstdlib>
#include <windows.h>
using namespace std;
srand(time(NULL)); 
int main(){
    int botguess;
    int playerinput;
    int mi=1, ma=100;
    int turns = 0;
    cout<<" what do you want guessed:";
    cin>> playerinput;
    cout<< "time for me to start guessingn";
    for(int i = 0;i < 50;i++) {
        botguess = rand() % ma + mi;
        if(playerinput > botguess){  //<--the problem 
            mi = botguess;
        }
        if(playerinput < botguess) {
            ma = botguess;
        }
        cout<<"Max:"<<ma<<"n"<<botguess<<"n";
        Sleep(1000);
        if(botguess == playerinput)
        {
            cout<<"you win";
        }
    }
    cin.get();
    return 0;
}

所以我一直在为为什么逻辑上这不起作用而烦恼。这是一个程序,应该猜到球员的号码,但不是立即。

我注意到的那行导致了一个错误,可能的最大数目被忽略了。我得到的数字是100+,但低于200,我不知道为什么。当我删除关于嵌套在for循环语句中的mi变量的行。程序没有超过100,但我没有得到程序的另一端解决球员号码。

如果你想明白了,你能解释给我听吗?我不只是想要一个答案。

botguess = rand() % (ma - mi + 1) + mi

你不想要ma不同的数字,你想要更少的。看一个例子:(5..10)包含6不同的数字:[5, 6, 7, 8, 9, 10];但是如果你做rand() % 10 + 5,你得到的是从5 (5 + 0)到14 (5 + 9)的数字。您需要的是rand() % 6 + 5,其中610 - 5 + 1

您遇到的问题是由于mi被设置为botguess,这很容易大于零,然后在下一个循环中,如果ma仍然是100(或接近它),您有时会将大于100的数字设置为botguess。

编辑添加:c++中的%操作符是mod除法(即。因此,例如,98% 100 + 15将是98 + 15,即113

此链接可能对您有所帮助:

http://www.cplusplus.com/reference/cstdlib/rand/