首页 > 解决方案 > 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;
}

标签: c++

解决方案


在这种情况下,该变量i仅在 for 循环内定义。

如果你愿意,你可以i在 do while 循环之前定义,然后在 for 循环中使用它,如下所示:

for(i = 0; i < 100; i++) {
...
}

建议:您可以尝试不使用 for 循环,并PlayerAns使用整数而不是数组。


推荐阅读