【问题标题】:How to avoid including an unwanted `+` separator in a label for my dice game?如何避免在我的骰子游戏标签中包含不需要的“+”分隔符?
【发布时间】:2015-12-17 07:03:30
【问题描述】:

我对一个简单的 Windows 窗体程序有疑问。该程序是一个骰子游戏:

  • 用户在文本框中输入他们想要掷多少个骰子。
  • 应用程序掷骰子的数量。
  • 该应用程序显示每个骰子的值以及标签中所有掷骰子的总和。

示例:如果我掷 4 个骰子,应用程序应显示它们的值及其值的总和,例如:4 + 3 + 6 + 1 = 14。

在写一个额外的+ 退出之前,我不知道如何让我的应用程序决定它是否掷骰子足够多。

现在,应用程序显示掷 3 个骰子的结果,如下所示:

3 + 3 + 3 += 9

但我不希望标签中的最后一个+ - 我希望它只写= 9,而不是+= 9。

这就是我的代码现在的样子:

private void throwDice_Click(object sender, EventArgs e)
{
    int numberOfDices = int.Parse(dicesTextBox.Text);
    int sum = 0;
    showLabel.Text = "";

    if (numberOfDices == 1)
    {
        Random rand = new Random();
        int dice1 = rand.Next(1, 7);
        sum = dice1;
        showLabel.Text = dice1 + " = " + sum;
    }
    else if (numberOfDices > 1)
    {
        Random rand1 = new Random();

        for (int i = 0; i <= numberOfDices; i++)
        {
            int dice = rand1.Next(1, 7);
            sum += dice;

            if (i != numberOfDices)
            {
                showLabel.Text += dice.ToString() + " + ";
            }
            else
            {
                showLabel.Text += "=" + sum.ToString();
            }
        }
    }
}

【问题讨论】:

    标签: c# winforms if-statement for-loop random


    【解决方案1】:

    只需将if (i != antal) 更改为if (i &lt; numberOfDices) 并将visaLabel.Text += "=" + summa.ToString(); 更改为visaLabel.Text += dice.ToString() + " = " + sum.ToString();。

    【讨论】:

      【解决方案2】:

      更优雅的方法可能是:

      private void throwDice_Click(object sender, EventArgs e)
      {
          int numberOfDices = int.Parse(dicesTextBox.Text);
          int sum = 0;
          int i = 1;
          showLabel.Text = "";
      
          do
          {
              Random rand = new Random();
              int dice1 = rand.Next(1, 7);
              sum += dice1;
              showLabel.Text += string.Format("{0} {1}", dice1.ToString(), i ==  numberOfDices ? " = " + sum.ToString() : " + ");
              i++;
          } while (i <= numberOfDices);       
      }
      

      【讨论】:

      • 要为掷骰子添加更多随机性,您可以调用:Thread.Sleep(100);在 i++ 之后;在while循环中。
      • 我发布了对原始答案的编辑。请确保 i++ 语句位于 do while 循环的末尾。
      猜你喜欢
      • 2023-01-26
      • 1970-01-01
      • 2012-02-29
      • 1970-01-01
      • 2016-01-16
      • 2016-12-26
      • 2021-12-14
      • 2015-08-25
      • 2015-12-24
      相关资源
      最近更新 更多