我需要有关获胜条件和随机安排团队相互对抗的帮助...我随机选择要玩的团队,我不断让相同的团队玩两次或自己玩,我不知道该怎么做
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <cmath>
#include <stdlib.h>
#include <sstream>
using namespace std;
struct teams{//declaring a struct for the teams
string side;
int number;
int number1;
}teams1[16], points[16];
//void intro screen(){//function for the introduction screen
void fileData(){//function for reading the teams data file
ifstream input;
input.open("FootballTeam.txt",ios::in); //associate file
if(input.is_open()){//opening the file
for(int x=0; x<16; x++){//looping through the file
input>>teams1[x].side;//getting info from the file
cout<<teams1[x].side<<endl;//printing out the data from the file
}//end for
}//end if
}//end void
void play(){//function for playing the game
srand(time(NULL));
for(int x=0; x<=1; x++){//loop for random teams to play
for(int s=0; s<=7; s++){//loop for randoms goals value
x=rand() %16+1;//randomly selecting two teams
points[s].number=rand()%4+1;//randomly selecting goals
points[s].number1=rand()%7+3;//randomly selecting goals
cout<<teams1[x].side<<" :"<<points[s].number<<" vs "
<<teams1[s].side<<" :"<<points[s].number1<<endl<<endl;//printing out the teams and goals
//cout<<teams1<<" Won this match"<<endl;
}//end for
}//end for
}//end void
int main (){
cout<<"ROUND OF 16 Finalists!!!\n"<<endl;
fileData();
cout<<"\n";
system("PAUSE");
system("CLS");
play();
return 0;
}//end main
最佳答案
如果您在使用 rand()
之前不调用 rand()
,则 rand()
伪随机数生成器将使用其默认种子>。为了防止 rand()
在每次运行程序时都使用默认种子,从而始终选择相同的团队对,您应该调用 srand()
并传入time(NULL)
,我看到你已经完成了。由于您的程序永远不会在同一时间运行两次,rand()
将在每次运行时输出不同的数字。
但是,请注意您应该只调用一次 srand()
。 因此您需要在程序启动后立即在 main()
中调用它。现在您每次都调用 srand()
时间 play()
被调用。每次调用 play()
之间的时间间隔可能非常小。因此,rand()
每次都以几乎相同的数字作为种子,因为时间差异太小了。这有效地在其伪随机数序列中的同一点开始了 rand()
,这就是为什么您会看到相同的球队在互相比赛。
int main() {
srand(time(NULL));
// now you're free to use rand() for the rest of the program
// ...
}
参见 this reference有关 srand()
的更多信息。
关于c++ - 需要帮助足球模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31398551/