需要帮助足球模拟

Need help soccer simulation

本文关键字:模拟 帮助      更新时间:2023-10-16

我需要帮助来创造获胜条件并随机安排团队相互对抗…我随机选择球队来比赛,我总是让同样的球队打两场比赛或自己打一场比赛,我不知道该怎么办

#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()之前不调用srand(),则rand()伪随机数生成器将使用其默认种子。为了防止rand()在每次运行程序时使用默认种子,从而总是选择相同的团队对,您应该调用srand()并传入time(NULL),我看到您已经这样做了。因为你的程序不会同时运行两次,rand()将在每次运行时输出不同的数字。

但是,请注意您应该只调用一次srand()所以你需要在main()中调用它,只要你的程序启动。现在每次调用play()时都调用srand()。每次调用play()之间的时间间隔可能非常小。因此,由于时间差太小,rand()最终每次都以几乎相同的数字播种。这有效地从伪随机数序列的同一点开始rand(),这就是为什么你看到相同的团队相互比赛。

int main() {
    srand(time(NULL));
    // now you're free to use rand() for the rest of the program
    // ...
}

查看srand()的更多信息