简体   繁体   English

C#骰子游戏,总和仅返回最后2卷的总和,而不是整个游戏

[英]C# Dice game, Sum returns only sum of last 2 rolls not whole game

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? 我正在创建一个带有2个骰子的骰子游戏,但我能正常工作,但唯一的问题是我无法从所有掷骰子中获得总和(整个游戏),如果我使用总和,我只会获得最后2个掷骰子的总和方法,我如何找到所有卷的总和? 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

If anyone has any idea how i can get the total roll sum please answer, greatly appreciated. 如果有人对我如何获得总积分有任何想法,请回答,不胜感激。

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. SumAverage扩展方法将计算数组中当前值的总和和平均值,由于每次尝试都将重置数组,因此它将仅包含最后两项。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM