簡體   English   中英

比較兩個數組中的項以查看它們的總和是否為 10

[英]Compare items from two arrays to see if they sum to 10

我想比較兩個“骰子”數組,看看有多少種方法可以使用兩個骰子創建 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 ;
            } 

如果我理解正確,您可以手動設置num1num2嗎?

您應該使用兩個循環,一個嵌套在另一個循環中。 然后在嵌套循環中應該有 if 語句來檢查數字總和是否為 10。

我不會給你代碼 - 試着自己弄清楚,如果你成功了,請告訴我:)

如果你還沒有想出解決方案,這里是:

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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM