即使在调用srand()时也没有得到不同的随机值

时间:2013-09-25 06:44:37

标签: c++

我刚刚开始学习C ++,我尝试制作一个小程序,随机选择哪些游戏和哪些团队投注体育赌博。我有一个比较两个随机数的函数,较大的值是游戏的选择结果。

该程序编译并运行,但由于某种原因,它总是最终选择一个结果,即HOME结果。有人可以查看我的代码并让我知道我做错了什么吗?我已经看了一段时间了,看不出问题。我认为它与双转换到int转换有关。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <ctime>

using namespace std;
inline void keep_window_open() { char ch; cin>>ch; }

int a;
int b;
int z;
int games_in_total (int, int);
double vector_home(int, int);
double vector_away(int, int);
string selection(double, double);

//takes user input with regard to how many games are playing and how many games you'd like to bet on

int main()
{ 

    cout << "How many games are there this week? " << endl;
    cin >> a;
    cout << "How many games do you want to bet on this week? " << endl;
    cin >> b;

    cout << " " << endl;

    //calls two functions in order to randomly pick which games to bet on and which team to choose within those games.

    z = 0;
    while (z < b){

    cout << "Pick game No." << games_in_total(a,b) << '\t' << "and choose" << selection((vector_home(a,b)), (vector_away(a,b))) << endl; 
    cout << " " << endl;
    ++z;

    }

    keep_window_open(); 
    return 0;

}

//randomly chooses games within the users input range
int games_in_total(int, int) {
    vector <int> games(0);
    srand (time(NULL));

    int i = 0;
    while(i<b){
    games.push_back(rand()% a+1);
    ++i;
        }

    return games[z];

}

//randomly assigns double values to the home team vector. Also adds 1.75 to the random number to give slight advantage to home teams.
double vector_home(int, int) {

    vector<double>home(0);
    srand (time(NULL));

    int i = 0;
    while(i<b){

    home.push_back((rand()% a+1) + 1.75);
    ++i;
    }

    return home[z];    
}

//randomly assigns double values to the away team vector
double vector_away(int, int) {
    vector<double>away(0);
    srand (time(NULL));

    int i = 0;
    while(i<b){

    away.push_back((rand()% a+1));
    ++i;
    }

    return away[z];
}

//compares the home team and away team vector values and assigns the larger values to the randomly chosen games to bet on.

string selection(double, double ){
    string pick_home;
    string pick_away;

    pick_home = " HOME.";
    pick_away = " AWAY.";

    if ((vector_home(a, b)) > (vector_away(a, b))){ 
         return pick_home;         
         }
    else 
         return pick_away;                  
}

1 个答案:

答案 0 :(得分:4)

  1. srand()初始化随机数生成器。
  2. time(NULL)返回1970年1月1日的秒数。
  3. 由于您在eache调用srand(time(NULL))之前调用rand(),并且您的程序可能会在不到一秒的时间内执行,在99,99 ...%中,您将最终初始化随机数生成器每次调用rand()之前相同的种子,因此rand()的结果在整个程序运行期间都是相同的。
  4. 从那时起,您将1.75添加到主页值,其值将始终大于离开值。
  5. 你需要做什么:

    • 从您的代码中删除所有现有的srand()来电
    • srand()
    • 中只调用一次main()