需要帮助足球模拟

时间:2015-07-14 05:48:18

标签: c++ simulation

我需要帮助一个胜利的条件并随机地让球队互相攻击...我随机选择球队参加比赛,我不断让同一支球队打两次比赛或者自己玩耍并且想要做什么

#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

1 个答案:

答案 0 :(得分:1)

如果在使用rand()之前未调用srand()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
    // ...
}

有关srand()的详细信息,请参阅this reference