【问题标题】:C# Adding the sum of 2 ArraysC#添加2个数组的总和
【发布时间】:2021-11-22 00:22:36
【问题描述】:

我想将用户自己填写的两个数组的总和添加到一个变量或第三个数组中,然后将其打印出来。这就是我所坚持的:

Console.Write("How many numbers do you want to add: ");
        int howmany = Convert.ToInt32(Console.ReadLine());
       
        int[] numarr1 = new int[howmany];
        int[] numarr2 = new int[howmany];
        int[] res = new int[1];

        for (int i = 0; i < numarr1.Length; i++)
        {
            Console.Write("Input a first number: ");
            int a = Convert.ToInt32(Console.ReadLine());

            numarr1[i] = a;            
        }
        for(int b = 0; b < numarr2.Length; b++)
        {
            Console.Write("Input a second number: ");
            int a = Convert.ToInt32(Console.ReadLine());

            numarr1[b] = a;
        }
        int result = numarr1 + numarr2;

除了我尝试添加它们的最后一行之外,一切正常。在互联网上,我正在搜索“如何将两个数组的和相加,但我并没有真正找到任何真正解决我问题的东西。

【问题讨论】:

标签: c# arrays


【解决方案1】:

使用Linq.Sum()怎么样

int result = numarr1.Sum() + numarr2.Sum();

或者只是在迭代期间添加值

Console.Write("How many numbers do you want to add: ");
int howmany = Convert.ToInt32(Console.ReadLine());
int[] numarr1 = new int[howmany];
int[] numarr2 = new int[howmany];
int[] res = new int[1];
int result = 0; // result here
for (int i = 0; i < numarr1.Length; i++)
{
    Console.Write("Input a first number: ");
    numarr1[i] = Convert.ToInt32(Console.ReadLine());
    result += numarr1[i];
}
for (int b = 0; b < numarr2.Length; b++)
{
    Console.Write("Input a second number: ");
    numarr2[b] = Convert.ToInt32(Console.ReadLine());
    result += numarr2[b];
}

【讨论】:

  • "Sum()" 加了下划线。
  • @Connor 添加using System.Linq;
  • 我输入的时候结果是5,我想加2个数字,所以前2个数字是2和3,后2个数字也是2和3,但结果是5,它必须是 10。
  • @Connor 附注,您的代码中有一个错误,第二个for 循环使用numarr1 而不是numarr2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
  • 2021-03-30
  • 1970-01-01
相关资源
最近更新 更多