How Do I Roll Dice in C#?

Simulating 10 Million Dice Rolls With C# Random Class

This application uses one instance of the Random() class in the object rnd. It also allocates enough space to hold the totals for scores 3..18 in the array Rolls[]. Member functions OneDice() returns a value between 1 and 6 - rnd.Next(n) returns values in the range 0..n-1, while ThreeDice() calls OneDice() three times. The constructor for the RollDice() clears the Rolls array then calls ThreeDice() however many times (10 million in this case) and increments the appropriate Rolls[] element.

The last part is to print out the generated totals to see that it generates throws in accordance with the probabilities. A 6 sided dice has an average score of 3.5, so three dice should average about 10.5. The totals for 10 and 11 are roughly the same and occur about 12.5% of the time.

Here is the output of a typical run. It takes no more than a second. Because it's a console application, I included a

``` Console.ReadKey();
```

To wait until you hit a key before closing.

Program Output

``` 3 46665 4 138772 5 277440 6 463142 7 693788 8 971653 9 1157160 10 1249360 11 1249908 12 1159074 13 972273 14 695286 15 463270 16 277137 17 138633 18 46439
```

Program Listing

``` using System; using System.Collections.Generic; using System.Text;   namespace exrand {     public class RollDice     {         private Random rnd= new Random() ;         private int[] Rolls = new int[19]; // Holds 3 to 18          public int OneDice() {             return rnd.Next(6)+1;         }          public int ThreeDice()         {             return OneDice() + OneDice() + OneDice() ;         }          public RollDice(int Count)         {             int i = 0;             for (i=3;i
```
Format
mla apa chicago