[英]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 ;
}
如果我理解正确,您可以手动设置num1
和num2
吗?
您应该使用两个循环,一个嵌套在另一个循环中。 然后在嵌套循环中应该有 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.