[英]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;
}
我通過main()跟隨程序,並且wins []充滿了所有相同的值,但是當我隔離draw()並跟隨循環時,數組正確地填充了隨機數...我不知道為什么嗎? 救命
只做一次 srand
。 如果您在循環中執行此操作,則會在循環中將種子重置為完全相同,這意味着rand
將一次又一次地產生相同的隨機數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.