简体   繁体   English

循环正确地填充数组,然后函数返回所有相同数字的数组?

[英]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?! 我通过main()跟随程序,并且wins []充满了所有相同的值,但是当我隔离draw()并跟随循环时,数组正确地填充了随机数...我不知道为什么吗? Help 救命

Do srand only once . 只做一次 srand 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. 如果您在循环中执行此操作,则会在循环中将种子重置为完全相同,这意味着rand将一次又一次地产生相同的随机数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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