1

我刚刚开始学习 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;                  
}
4

1 回答 1

4
  1. srand()初始化随机数生成器。
  2. time(NULL)返回 1970 年 1 月 1 日的秒数。
  3. 由于您在每次调用srand(time(NULL))之前调用rand()并且您的程序可能会在不到一秒的时间内执行,因此在 99,99...% 中,您最终将在每次调用之前使用相同的种子初始化随机数生成器,rand()因此结果rand()将在程序的整个运行过程中保持相同。
  4. 从那以后你1.75加到home值上,它的值永远会大于away值。

你必须做的:

  • srand()从您的代码中删除所有现有的调用
  • srand()只打一次电话main()
于 2013-09-25T07:02:30.477 回答