c++ - C ++使用用户输入数组检查while条件
问题描述
我是一名高中生,我想通过猜测随机数来制作简单的游戏,但我在需要检查条件时遇到了用户输入数组的问题。在检查条件时,它说没有声明 i。下面我留下代码。
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
int PlayerAns[200];
int iNumSecret, iNumGuess;
int iWrongAns = 0;
srand(time(NULL));
int iNumMax = 100;
iNumSecret = rand() % iNumMax + 1;
cout << "========== Simple Game =========== "
<< "\n";
do
{
for (int i = 0; i < 100; i++)
{
cout << "Guess the number od 1 do " << iNumMax << "\n";
cin >> PlayerAns[i];
if (iNumSecret < PlayerAns[i] && PlayerAns[i] >= 0 && PlayerAns[i] <= 100)
{
cout << " - Secret number is lower ! "
<< "\n";
}
else if (iNumSecret > PlayerAns[i] && PlayerAns[i] >= 0 && PlayerAns[i] <= 100)
{
cout << " - Secret number is higher ! "
<< "\n";
}
else if (PlayerAns[i] < 0 || PlayerAns[i] > 100)
{
cout << " - Number is out of scope ! "
<< "\n";
iWrongAns++;
}
}
}
while (iNumSecret != PlayerAns[i]);
{
cout << "--- You get it !!!"
<< "\n";
cout << PlayerAns << "\n";
cout << "You guess number out of scope that many times: " << iWrongAns << "\n";
}
return 0;
}
解决方案
在这种情况下,该变量i
仅在 for 循环内定义。
如果你愿意,你可以i
在 do while 循环之前定义,然后在 for 循环中使用它,如下所示:
for(i = 0; i < 100; i++) {
...
}
建议:您可以尝试不使用 for 循环,并PlayerAns
使用整数而不是数组。
推荐阅读
- javascript - 与服务器通信
- python - 如何在没有明确定义的字段值的情况下初始化字典
- c++ - 如果将其用作 Map 中的键,为什么使用不是 const 的操作数 < 函数定义结构会破坏事情?
- typescript - 从 node_modules 导入时,如果没有“new”,就不能调用类构造函数 Rectangle
- css - 不能在另一个图像上重叠多个图像?
- yarnpkg - 如何在同一台机器上安装 Yarn v1 和 Yarn v2 以便它们可以在项目之间互换使用?
- java - 如何覆盖 Spring Security 中特定端点的角色?
- python - 使用 Python 请求与 suiteCRM API V7.9 交互
- java - 使用简单的 for 循环将列表中的搜索转换为流方法
- angular - 我需要知道如何从其他函数调用值