C#技术问题:如何从数组A生成前缀和数组B?附已实现代码
问题解决思路与代码实现
首先先修正原代码中的两处小问题:
- 生成1-100随机数时,
randNum.Next(min, max)是左闭右开区间,原代码min=0会生成0-99的数,应该把min设为1,max设为101才能得到1-100的随机整数。 - 统计小于10的元素数量时,原代码用了
Distinct(),这会去除重复值后计数,不符合“统计元素数量”的需求,应该去掉Distinct()。
接下来是数组B(前缀和数组)的实现,有两种常用方式:
方法一:手动循环实现
这是最直观的方式,通过维护一个累加变量,遍历数组A的同时计算每个位置的前缀和并赋值给数组B:
// 创建数组B int[] arrayB = new int[5]; int currentSum = 0; for (int i = 0; i < arrayA.Length; i++) { currentSum += arrayA[i]; arrayB[i] = currentSum; } // 打印数组B验证结果 Console.WriteLine("数组B的元素为:"); foreach (int num in arrayB) { Console.WriteLine(num); }
方法二:使用LINQ的Scan方法
如果熟悉LINQ,可以用Scan方法直接生成前缀和序列,代码更简洁:
// 确保已引用System.Linq命名空间 using System.Linq; // 生成前缀和数组B int[] arrayB = arrayA.Scan(0, (acc, num) => acc + num).Skip(1).ToArray(); // 打印数组B验证结果 Console.WriteLine("数组B的元素为:"); foreach (int num in arrayB) { Console.WriteLine(num); }
解释:Scan方法会从初始值0开始,依次将当前累加值和数组元素相加,生成包含初始值的序列(比如A=[1,2,3]会生成[0,1,3,6]),所以用Skip(1)去掉第一个初始值,再转成数组就是我们需要的B数组。
完整修正后的代码
using System; using System.Linq; class Program { static void Main() { Console.WriteLine("This program fills an array A of size 5 with random integers in the range 1 to 100 and prints it out"); int[] arrayA = new int[5]; int min = 1; int max = 101; Random randNum = new Random(); Console.WriteLine("数组A的元素为:"); for (int i = 0; i < arrayA.Length; i++) { arrayA[i] = randNum.Next(min, max); Console.WriteLine(arrayA[i]); } int sum = arrayA.Sum(); Console.WriteLine("The sum of the array elements is " + sum); int count = arrayA.Where(x => x < 10).Count(); Console.WriteLine("The number of less than 10 value array elements is " + count); // 实现数组B(手动循环方式) int[] arrayB = new int[5]; int currentSum = 0; for (int i = 0; i < arrayA.Length; i++) { currentSum += arrayA[i]; arrayB[i] = currentSum; } Console.WriteLine("数组B的元素为:"); foreach (int num in arrayB) { Console.WriteLine(num); } } }
内容的提问来源于stack exchange,提问作者Emil Ko
相关产品推荐
相关产品推荐

