I'm trying to create a program that simulates a season of baseball. It takes a text input from a file that has the stats of the player, like Batting Average, Fielding Percentage, Home Runs etc... So i have planned everything except the simulating part. I need to figure out a way to make the program have a way of giving the batter a Homerun, Single, Double, etc. One idea i got was that i could each batter have a random number for each stat, for example player xyz has a batting average of .333 so therefore we make a random number generator in the range between 1 and 3 then we would make an if statement that stated if the batting average of player xyz was 1 then he would get a hit. But there are many problems with this, the obvious one, a LOT of code for not a very complex task, another what if the batting average is another number like .280 then what number range would you use?
So i was wondering if anybody had a solution for this , or an easier way to do this.

My idea, which is most likely the long and hard way, would be to convert the average to a fraction. .280 = 7/25. I would then try this:

Random r = new Random();
hitChance = r.Next(1,26);
if (hitChance < 8) 
{
    // Hit Code
}
else if (hitChance > 7) 
{
    // Out Code
}

This would be my way of going about this, however I am new to C# and relatively new to programming so you may want to ask a more senior programmer/poster.

yeah that could work but still thats for one stat of one player and each player has 5 stats and theres 9 players on a team and theres many teams so thats a lot of code, but this is what ill use as a last resort if i cant figure out an easier way, so anybody else got an idea?

I just though of an easier way that requires less work and a little less code.

average = .280 * 1000;  
Random r = new Random();
int hitChance = r.Next(1,1001);
if (hitChance < average+1) 
{
//Hit
}
else 
{
//Out
}

This should be a little easier because you avoid fractions and there is more consistency between the code for each player.

How did i not think of that!?
Anyways thanks for the help, and ill use this in my code if you dont mind.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.