我如何从课堂上归还总和

时间:2014-03-22 14:06:48

标签: c#

我正在编写一个程序,用户写下他想要扔多少次x号骰子以及他们将要有多少方。

但是我无法弄清楚如何在每个骰子游戏中返回数字总和..

这是主要代码:

static void Main(string[] args)
{
    List<Dice> _Dice = new List<Dice>();
    int a = 0;
    int ggr = int.Parse(Interaction.InputBox("How many times do you want to repeat:"));
    while (a != ggr)
    {
    int xChoice = int.Parse(Interaction.InputBox("How many dice do you want to throw:"));
    int yChoice = int.Parse(Interaction.InputBox("Write how many sides the dice will have:"));

    _Dice.Add(new Dice(xChoice,yChoice));
    a++;
    }
    int e = 1;
    foreach (var item in _Dice)
    {
        Interaction.MsgBox(string.Format("Result off game {0}: {1}", e++, item.ToString()));
    }

}

这是Dice类:

    static int _xChoice, _yChoice;
    static int[,] dice = new int[_xChoice, _yChoice];
    public int Tostring()
{
    int a = 0;
    foreach (var item in dice)
    {
        a+=item;
    }
    return a;
}
    void throw()
    {
      Random r = new Random();
      for (int i = 0; i <dice.GetLength(0); i++)
        {
            for (int j  = 0; j < dice.GetLength(1); j++)
            {
                dice[i, j] = r.Next(1, _yChoice); 
            }
        }

  }

    public Dice(int Xchoice, int Ychoice)
    {
        _xChoice = Xchoice;
        _yChoice = Ychoice;
    }

2 个答案:

答案 0 :(得分:1)

为了完整起见,您要求的是2D array的项目总和:

int total = Enumerable.Range(0, _xChoice).Sum(s => Enumerable.Range(0, _yChoice).Sum(p => dice[s, p]));

答案 1 :(得分:0)

你可以这样做:

 void throw()
    {

      Random r = new Random();
      for (int i = 0; i <dice.GetLength(0); i++)
        {
            int totalSum = 0;
            for (int j  = 0; j < dice.GetLength(1); j++)
            {
                dice[i, j] = r.Next(1, _yChoice);
                totalSum += dice[i, j];
            }
            // Here you display totalSum for game with index i.
        }

  }