我想比較兩個“骰子”陣列,看看有多少種方法可以使用兩個骰子創建 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 ;
}
uj5u.com熱心網友回復:
如果我理解正確的話,你可以設定num1和num2手動?
您應該使用兩個回圈,一個嵌套在另一個回圈中。然后在嵌套回圈中應該有 if 陳述句來檢查數字總和是否為 10。
我不會給你代碼 - 試著自己弄清楚,如果你成功了,請告訴我:)
uj5u.com熱心網友回復:
如果你還沒有想出解決方案,這里是:
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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336432.html
