首页 > 解决方案 > 正确制作 AI 循环?

问题描述

我正在为猜谜游戏制作 AI,但遇到了一个我似乎无法自行解决的问题。目标是让用户在合理的时间内输入一个数字供 AI 猜测,我生成一个介于 1-100 之间的随机数并通过循环运行它以调整更低或更高。

void AI::AIguess(int usernum)
{
        srand(time(NULL));
        AIchoice = rand() % High + Low;
    // "too high" or "too low" accordingly
    do {
        if (AIchoice == usernum)
        {
            cout << AIchoice << " is this correct?" << endl;
        }
        else if (AIchoice <= usernum)
        {
            cout << AIchoice << " seems a little low.." << endl;
            Low = AIchoice;
            AIchoice = 0;
            AIchoice = rand() % High + Low;
            AIguesses++;
        }
        else if (AIchoice >= usernum)
        {
            cout << AIchoice << " might have overshot a bit :/" << endl;
            High = AIchoice;
            AIchoice = 0;
            AIchoice = rand() % High + Low;
            AIguesses++;
        }
    } while (AIchoice != usernum);
}

我正在使用之前生成的号码作为下一个生成号码的参数,以希望获得用户号码。它在 if 语句之间弹跳良好并分别调整了高和低,但我面临的问题是经过几次循环后 AIchoice 开始添加超过 100。有人能帮我吗?

PS:非常感谢任何有用的 AI 创建信息 :)

标签: c++visual-c++

解决方案


您在区间代码中的随机数是错误的。要生成 和 之间的数字minmax请执行(rand() % (max - min)) + min

所以 AIchoice = rand() % High + Low; 改为 AIChoice = (rand() % (High - Low)) + Low;.


推荐阅读