简体   繁体   中英

Loop fills array correctly then function returns array of all the same numbers?

#include <iostream>
#include <ctime>

int *initialize(int []);
bool check(int random_num, int []);
int *draw(int []);
int *printout(int user_input, int []);
int entry(int user_input);

using namespace::std;

int wins[10]; // sets global array
int random_num; //stores global var for random numbers
int user_input; //stores global var for user entered number

int main(){
    int nothing; // used to pause program
    initialize(wins);
    draw(wins);
    entry(user_input);
    check(user_input, wins);
    printout(user_input, ::wins);
    cin >> nothing; // used to pause program
}

//Initializes the array wins[] with the value -1
int *initialize(int wins[]){
    for (int i = 0; i < 10; ++i)
        ::wins[i] = {-1};
    return ::wins;
}
// draws 10 random numbers and fills the array with them
int *draw(int wins[]){
    for (int i = 0; i < 10; i++){
        srand(time(NULL));
        ::random_num = rand() % 100;
        ::wins[i] = ::random_num;
    }
    return ::wins;
}
//Allows the user to enter a number and stores the number entered
int entry(int user_input){
    cout << "Pick a number between (0 and 99): ";
    cin >> ::user_input;
    return ::user_input;
}
//Checks to see if the number guessed is a winning number
bool check(int user_input, int wins[]){
    for (int i = 0; i <= 10; i++){ // starts evaluating from win[0]
        if (::user_input == ::wins[i]){ // checks for matching numbers to decide if winner
            cout << "Number selected: " << user_input << endl << "You win!";
            return true;
        }
        if (::user_input != ::wins[i]){ // checks for mis-matching numbers to decide if loser
            cout << "Number selected: " << user_input << endl << "You lose!";
            return false;
        }
    }
}
// Sends the selected lottery numbers to the user in a spaced format
int *printout(int user_input, int wins[]){
    cout << endl << "Lottery numbers: ";
    for (int i = 10; i >= 0; i--)
        cout << ::wins[i] << " ";
    return ::wins;
}

I followed the program through main() and wins[] was filled with all the same values but when I isolated draw() and followed the loop the array filled correctly with random numbers... I cannot figure out why?! Help

Do srand only once . If you do it in a loop you reset the seed to exactly the same in the loop, which means rand will produce the same random number over and over again.

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