C++ 如何在C++;设置为0并防止其变得随机?

C++ 如何在C++;设置为0并防止其变得随机?,c++,variables,random,int,C++,Variables,Random,Int,我是编程的初学者。我在做一些简单的应用程序。当我意识到我的变量变得随机时,我已经完成了我的程序,即使我将它设置为0。我想弄清楚原因。我的目标是将1添加到“cor”变量中,当答案与随机生成的数字匹配时,“else”部分按其必须的方式工作。也许有更有经验的人能帮我 ` #包括 #包括 #包括 #包括 使用名称空间std; 整数; int-ynumber[5]; int cor=0; int-falsed=0; int main() { 库特 数组的长度为5 数组中有多少个元素ynumber?循环中有

我是编程的初学者。我在做一些简单的应用程序。当我意识到我的变量变得随机时,我已经完成了我的程序,即使我将它设置为0。我想弄清楚原因。我的目标是将1添加到“cor”变量中,当答案与随机生成的数字匹配时,“else”部分按其必须的方式工作。也许有更有经验的人能帮我

`

#包括
#包括
#包括
#包括
使用名称空间std;
整数;
int-ynumber[5];
int cor=0;
int-falsed=0;
int main()
{
库特
数组的长度为5


数组中有多少个元素
ynumber
?循环中有多少个元素?最好将
for(int i=0;i<6;i++)
更改为
for(int i=0;i<5;i++)
,因为您有
int ynumber[5]
另外,不要使用全局变量,定义变量时尽量靠近使用它们的位置。顺便说一句,使用当前代码,您实际上根本不需要数组。一个简单的变量
int-ynumber;
就够了。这当然也可以通过超出数组的边界来解决问题。谢谢你我在更改数组中的数字时忘记了;)。@MateuszDettlaff使用
std::size
巧妙地避免了这个问题:)
#include <iostream>
#include <string>
#include <time.h>
#include <Windows.h>

using namespace std;

int number;
int ynumber[5];
int cor = 0;
int falsed = 0;

int main()
{
    cout << "Welcome to our lottery!" << endl; 

    cout << "We start in ..." << endl;
    Sleep(2000);


    for (int i = 3; i >= 0; i--)
    {
        system("cls");
        cout << i << endl;
        Sleep(1000);
    }

    system("cls");
    srand(time(NULL));

    for (int i = 0; i < 6; i++)
    {
        cout << "Type your " << i+1 << " number below" << endl;
        cin >> ynumber[i];

        number = rand() % 50 + 1;
        cout << "The picked number is: " << number << endl;
        Sleep(1000);

        if (ynumber[i] == number)
        {
            cout << "Same same!" << endl;
            cor = cor + 1;
        }
        else
        {
            cout << "Hope for better luck next time ;)" << endl;
            falsed = falsed + 1; 
        }
    }

    system("cls");

    cout << "Thank you for participating!" << endl << "Correct picked numbers: " << cor << endl << "Wrong picked numbers: " << falsed << endl << endl;

    system("pause");

    return 0;
}
int ynumber[5];
for (int i = 0; i < 6; i++)
{
//...
     cin >> ynumber[i];
for (int i = 0; i < std::size(ynumber); i++)