简体   繁体   中英

C++ Random Number Generator in Array

I'd like to write a program in C++, which will present 6 random numbers from 1 to 54. Below you could find the code. For some strange reason, when I run the program, I sometimes stumble upon an output like this:

Bugunku sansli loto sayiniz: 17 1 12 32 33 3418568

I couldn't figure out why the last number ignores my rule. Any help would be appreciated.

#include <cstdlib>
#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    cout << "Bugunku sansli loto sayiniz: " << endl;
    srand(time(0)); 
    int myArray [5];
    for (int i = 0; i < 6; i++)
    {
        myArray [i] = (rand() % 55) + 1;
        cout << myArray [i] << '\t';
    }
}

I couldn't figure out why the last number ignores my rule.

Because the last number accessed in the for loop is getting out of the bound of the array, dereference on it leads to UB. The for loop should be

for (int i = 0; i < 5; i++)
                    ~

Then i will be 0 ~ 4 , loop 5 times, not 6 times as your code shown.

You might use range-based for loop (since C++11) to avoid such kind of mistake:

for (auto& i : myArray) {
    i = (rand() % 55) + 1;
    cout << i << '\t';
}

random numbers from 1 to 54

So this is incorrect as well: (rand() % 55) + 1;

You'll need (rand() % 54) + 1;

Because you went to myArray[5] at the last time and your array don't have this place so you got it

you need to write like that:

#include <cstdlib>
#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    cout << "Bugunku sansli loto sayiniz: " << endl;
    srand(time(0)); 
    int myArray [5];
    for (int i = 0; i < 5; i++)
    {
        myArray [i] = (rand() % 55) + 1;
        cout << myArray [i] << '\t';
    }
}

If you want 6 items you need to make a array for six items

    int myArray[5];

this will provide 5 items where as

    int myArray[6]; 

this will provide you 6 items This will fix your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM