dimanche 1 mars 2020

C++ rand() returns nonsensical values on first run, works fine on second

I am in the middle of making a lottery program and this is my randomization function

#include <iostream>
#include <stdlib.h>
#include <time.h>// for seeding srand
#include <algorithm> //for std::find
#include <iterator> //for std::begin, std::end

using namespace std;

void rivinArvonta(int arvottuRivi[]){   
    int rivi[7];
    int pallo = 41;
    srand(time(NULL));

    for (int i = 0; i < 7; i++) {
            pallo = rand() % 40 + 1;
            bool exists = (find(begin(rivi), end(rivi), pallo) != end(rivi));
            if (exists == false) {
                    rivi[i] = pallo;
            }else
                    i = i - 1;
    }
    sort(rivi, rivi + 7);


    for (int i = 0; i < 7; i++){
        arvottuRivi[i] = rivi[i];
    }
}

The program runs in a while loop until I tell it to stop. The first time I call this function, it returns something like 5, 0, -164820691, 21983, 0, 0, -164820768. The second time I call the function it works just as intended.

I don't understand how pallo = rand() % 40 + 1; can return something so much out of the bounds? Could this be because I use g++?

PS sorry for having my variable names in finnish.




Aucun commentaire:

Enregistrer un commentaire