数字猜谜游戏与不合逻辑的错误
Number guessing game with illogical bug
#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
,其中6
是10 - 5 + 1
。
您遇到的问题是由于mi被设置为botguess,这很容易大于零,然后在下一个循环中,如果ma仍然是100(或接近它),您有时会将大于100的数字设置为botguess。
编辑添加:c++中的%操作符是mod除法(即。因此,例如,98% 100 + 15将是98 + 15,即113
此链接可能对您有所帮助:
http://www.cplusplus.com/reference/cstdlib/rand/相关文章:
- C++选择排序算法中的逻辑错误
- 尝试创建表会给出 SQL 逻辑错误
- 使用动态数组时C++逻辑错误
- 尝试从 Visual Studios C++ 中的加密字符串输出解密字符串时出现逻辑错误
- C ++函数重新定义(代码不起作用 - 逻辑错误)
- 我如何在一个 if 语句中声明所有数字我尝试通过其他方式声明所有数字,如果一个接一个,但似乎代码有逻辑错误
- 需要一些帮助来查找我的程序中的逻辑错误
- 我正在调试这个C++程序.编译器不再显示语法错误,但存在隐藏的逻辑错误
- C++ 中连接 4 游戏的输入逻辑错误
- C++ 中计时的逻辑错误(使用 std::chrono)
- 无法在代码厨师七月挑战中找到我的逻辑错误
- 如何在以下代码中修复此逻辑错误
- 仅在Android上查询时SQL逻辑错误
- 逻辑错误,我将获得意外结果
- 标准::替换的逻辑错误
- C++ Visual 工作室中的逻辑错误.阵列打印的是地址而不是内容
- 通过迷宫求解程序回溯逻辑错误
- 检查输入是否为字母数字时的逻辑错误
- 显示使用函数、switch 语句和多维数组的程序的多个不合逻辑的错误
- 数字猜谜游戏与不合逻辑的错误