【问题标题】:Compare items from two arrays to see if they sum to 10比较两个数组中的项目以查看它们的总和是否为 10
【发布时间】:2021-12-09 06:46:48
【问题描述】:

我想比较两个“骰子”数组,看看有多少种方法可以使用两个骰子创建 10 的总和,然后将“10 对”的数量添加到另一个变量中。

这是我目前所拥有的,我不确定如何启动 forEach 循环(或者这是否是我想要使用的):

            {
                //Store 10-pairs in a new variable
                int tenPairs = 0;

                // Need variables to define the dice - arrays starting at 1?
                int[] die1 = Enumerable.Range(1, num1).ToArray(); 

                int[] die2 = Enumerable.Range(1, num2).ToArray();

                //Compare each item from die1 to each value from die2 to see if they
                //add up to 10.




                //return a string with the message: "There are X total ways to get the sum 10."
                string resultMsg = "There are " + tenPairs +" total ways to make 10.";
                
                return resultMsg ;
            } 

【问题讨论】:

    标签: c# arrays loops


    【解决方案1】:

    如果我理解正确,您可以手动设置num1num2

    您应该使用两个循环,一个嵌套在另一个循环中。然后在嵌套循环中应该有 if 语句来检查数字总和是否为 10。

    我不会给你代码 - 试着自己弄清楚,如果你成功了告诉我:)

    【讨论】:

    • 感谢您的提示 - 我使用了一些带有 if 语句的嵌套 for 循环来执行算术运算。再次感谢您的帮助!
    【解决方案2】:

    如果你还没有想出解决办法,这里是:

    private static string NumberOfTens(int number1, int number2)
        {
          //Store 10-pairs in a new variable
          int tenPairs = 0;
    
          // Need variables to define the dice - arrays starting at 1?
          int[] die1 = Enumerable.Range(1, number1).ToArray();
    
          int[] die2 = Enumerable.Range(1, number2).ToArray();
    
          //Compare each item from die1 to each value from die2 to see if they add up to 10.
    
          for (int i = 0; i < die1.Length; i++)
          {
            for (int j = 0; j < die2.Length; j++)
            {
              if (die1[i] + die2[j] == 10)
              {
                tenPairs++;
              }
            }
          }
    
          //return a string with the message: "There are X total ways to get the sum 10."
          string resultMsg = "There are " + tenPairs + " total ways to make 10.";
    
          return resultMsg;
        }
    

    这里是如何使用它:

    Console.WriteLine(NumberOfTens(5, 15));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多