C#实现两个用户输入数组的求和并存入变量或第三个数组求助
C#两个数组对应元素求和实现方案
现有代码存在的问题
- 第二个输入循环赋值错误:收集第二个数组的用户输入时,你将值写入了
numarr1,覆盖了第一个数组的已有数据,需要改为赋值给numarr2。 - 数组直接相加不符合语法:C#不支持直接用
+运算符对两个整数数组做运算,无论是逐元素相加还是整体求和都需要遍历数组处理。
实现代码(支持两种输出需求)
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[] sumArr = new int[howmany]; // 所有元素相加的总结果 int totalSum = 0; // 收集第一个数组输入 for (int i = 0; i < numarr1.Length; i++) { Console.Write($"Input the {i+1}th number for first array: "); numarr1[i] = Convert.ToInt32(Console.ReadLine()); } // 收集第二个数组输入 for(int b = 0; b < numarr2.Length; b++) { Console.Write($"Input the {b+1}th number for second array: "); numarr2[b] = Convert.ToInt32(Console.ReadLine()); } // 遍历计算 for(int i = 0; i < howmany; i++) { // 逐元素相加存入第三个数组 sumArr[i] = numarr1[i] + numarr2[i]; // 累加得到总结果 totalSum += sumArr[i]; } // 输出结果 Console.WriteLine("===== 计算结果 ====="); Console.WriteLine($"两个数组对应元素相加的总和:{totalSum}"); Console.WriteLine("逐元素相加的结果数组:"); foreach(var item in sumArr) { Console.Write(item + " "); }
你可以根据自己的需求选择输出总结果或者第三个数组的内容即可。
内容的提问来源于stack exchange,提问作者user17040797
相关产品推荐
相关产品推荐

