I'm creating a dice game with 2 dice, i have got it working but only problem is i cant seam to get the Sum from all the rolls(whole game), i only get the sum of last 2 rolls if i use the Sum method, how do i find the Sum of all the rolls? Here's my code:
Console.BufferHeight = 500;
Random x = new Random();
int throw_times = 1;
int[] dice = new int[2];
dice[0] = x.Next(1, 7);
dice[1] = x.Next(1, 7);
for (int i = 1; i <= 100; i++)
{
dice[0] = x.Next(1, 7);
dice[1] = x.Next(1, 7);
int total_var = dice[0] + dice[1];
int[] total_array = {dice[0] + dice[1]};//total in array
Console.Write("Throw " + throw_times + ": " + dice[0] + " and " + dice[1] + " = ");
Console.WriteLine(total_var);
throw_times++;
Array.Sort(dice);
for (int a = dice.Length - 1; a >= 0; a--)
{
int s = dice[a];
Console.WriteLine("#" + s);
}
}
Console.WriteLine("Total sum: " + dice.Sum());//only returns sum of last 2 rolls
Console.WriteLine("Average: " + dice.Average());//only return average of last 2 rolls
The Sum
and Average
extension methods will compute the sum and average of what's currently in the array, and because you're re-setting the array with every trial, it will only ever contain the last two items.
To get the sum or average of all the dice rolls, you'd either have to expand your array so that it records all the dice rolls made throughout your program, or just keep a running total (which seems a lot simpler):
int[] dice = new int[2];
int sum = 0;
for (int i = 1; i <= 100; i++)
{
dice[0] = x.Next(1, 7);
dice[1] = x.Next(1, 7);
sum += dice[0] + dice[1];
...
}
Console.WriteLine("Total sum: " + sum);
Now it's not entirely clear from your question if you also want the average of all the dice rolls, or just the last two, but since you know the sum and you know the total (because that's hard coded in your app), you can compute the average of all dice rolls pretty easily:
Console.WriteLine("Total sum: " + (sum / 200)); // 200 because you roll 2 dice in 100 trials
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.