【问题标题】:Loop fills array correctly then function returns array of all the same numbers?循环正确填充数组然后函数返回所有相同数字的数组?
【发布时间】:2015-05-07 03:32:49
【问题描述】:
#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() 并遵循循环时,数组正确填充了随机数......我不知道为什么?!帮助

【问题讨论】:

  • 为什么是全局变量?使用您已经设置的参数。
  • 为什么要使用全局变量?您将参数传递给函数,以及一些仅在单个函数中使用的全局变量,这意味着您应该使用 local 变量。
  • 这项作业有一些我最初试图解决的限制。我现在要让它与局部变量一起工作。谢谢!

标签: c++ arrays


【解决方案1】:

只执行srand一次。如果您在循环中执行此操作,您将在循环中将种子重置为完全相同,这意味着rand 将一遍又一遍地产生相同的随机数。

【讨论】:

  • 哇,真的就是这么简单……我花了很多时间来回溯这个程序。我想我需要更好地了解时间和 srand 是如何工作的!非常感谢!
  • @Matthew time 函数以 为单位返回时间,如果您在同一秒内多次调用它(如在一个小循环中),那么它将返回相同的值。
猜你喜欢
  • 1970-01-01
  • 2015-09-22
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
相关资源
最近更新 更多