我刚开始学习 C++,我尝试制作一个小程序,随机选择要为体育博彩投注的游戏和球队。我有一个比较两个随机数的函数,较大的值是游戏的选择结果。
程序编译并运行,但由于某种原因,它总是最终选择一个结果,即 HOME 结果。有人可以查看我的代码并让我知道我做错了什么吗?我已经看了一段时间了,看不出问题所在。我认为这与 double 到 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;
}
最佳答案
srand()
初始化随机数生成器。time(NULL)
返回自 1970 年 1 月 1 日起的秒数。- 因为您在每次调用
rand()
之前调用了srand(time(NULL))
并且您的程序可能会在不到一秒内执行,即 99,99 ...% 你最终会在每次调用rand()
之前使用相同的种子初始化随机数生成器,因此rand()
的结果将是相同的在程序的整个运行过程中。 - 从那时起,您将
1.75
添加到主场值,它的值将始终大于客场值。
你必须做的:
- 从您的代码中删除对
srand()
的所有现有调用 - 在
main()
中只调用一次srand()
关于c++ - 即使调用 srand() 也没有得到不同的随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18998003/