【问题标题】:Need help soccer simulation需要帮助足球模拟
【发布时间】:2015-10-02 14:43:38
【问题描述】:

我需要帮助来确定获胜条件并随机安排球队相互对抗...我随机选择球队参加比赛,我不断让相同的球队参加两次比赛或自己比赛,然后不知道该怎么办

#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

【问题讨论】:

  • 谢谢你帮了大忙

标签: c++ simulation


【解决方案1】:

如果您在使用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() 的更多信息,请参阅this reference

【讨论】:

    猜你喜欢
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2023-03-03
    相关资源
    最近更新 更多