X 变量在最后一次尝试简单猜谜游戏时发生变化,C++

X variable changes on the last try of simple guessing game, C++

本文关键字:游戏 变化 C++ 变量 最后一次 简单      更新时间:2023-10-16

我对编码和C++有点陌生。我试图制作一个猜谜游戏,将以前的猜测存储在一个数组中,该数组将在每次尝试失败后显示。

问题是,无论我输入

什么,第三次尝试将始终注册为正确,并且x变量(即随机数(将更改为我输入的任何内容作为y[2]。在我将数组添加到 y 变量之前,代码运行良好,并调整了代码的其余部分以适应它。

我还对变量进行了调试。非常感谢任何和所有的帮助。谢谢!;)

//Generating Random Number:
#include <cstdlib>  // or <stdlib.h>
#include <ctime>    // or <time.h>
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
    int x;
    int y[2];
    int z = 3;
    int i;
    bool done = false;
    srand(time(NULL));      
    x = rand() % 10 + 1;
    i = 0;
    int s;
    s = x;
    while (done == false)
    {
        cout << "Guess a number between 1 to 10.n";
        switch (i)
        {
            case 0: break;
            case 1:
                cout << "Previous guesses:n" << y[0] << endl << endl; break;
            case 2:
                cout << "Previous guesses:n" << y[0] << endl << y[1] << endl << endl; break;
        }
        cin >> y[i];
        cout << "y[" << i << "] = " << y[i] << endl;
        cout << "s = " << s << endl;
        if (y[i] > s)
        {
            z--;
            i++;
            cout << "nLower!n" << "Tries remaining: " << z << endl << endl;
            if (z == 0)
            {
                cout << "nSorry! You ran out of tries. :(";
                Sleep (2000);
                done = true;
            }
        }
        else if (y[i] < s)
        {
            z--;
            i++;
            cout << "nHigher!n" << "Tries remaining: " << z << endl << endl;
            if (z == 0)
            {
                cout << "nSorry! You ran out of tries. :(";
                Sleep (2000);
                done = true;
            }
        }
        else if (y[i] == s)
        {
            cout << "i = " << i << endl;
            cout << "nCongratulations!n" << "Your number is " << y[i] << ".n" << "Tries remaining: " << z;
            done = true;
        }
    }
    return(0);
}

int y[2]表示您创建一个大小为 2 的数组(可以容纳两个元素(。

更重要的是,vectorstd::array比内置数组更受欢迎