C#控制台开发:如何逐行填充矩阵?代码问题求助
解决C#二维矩阵填充问题:店铺季度利润统计程序
你这段代码的问题主要出在最后那个嵌套循环和数组索引的使用上,咱们一步步捋清楚:
核心问题分析
- 多余的嵌套循环:你外层已经在遍历每个店铺(
i就是当前店铺的索引),但后面又套了for (int k = 0; k < numberOfShops; k++),这会把所有店铺的数据都覆盖成当前输入的这家,完全没必要。 - 数组越界错误:
shop[array.Length]这里,数组索引是从0开始的,比如array.Length是4(四个季度),那最大索引是3,你直接用array.Length当索引肯定会抛出越界异常,而且你本来应该用循环变量m来对应每个季度的位置。 - 冗余的中间数组:其实不需要额外创建
shop数组,拆分输入后可以直接赋值到二维数组里,能简化代码。
修正后的完整代码
class Program { static void Main(string[] args) { const int numberOfTrimesters = 4; int numberOfShops = Convert.ToInt32(Console.ReadLine()); double[,] shopsList = new double[numberOfShops, numberOfTrimesters]; // 填充二维数组 for (int i = 0; i < numberOfShops; i++) { string input = Console.ReadLine(); string[] profitStrs = input.Split(' '); // 遍历当前店铺的4个季度 for (int m = 0; m < numberOfTrimesters; m++) { // 直接把拆分后的字符串转成double赋值到二维数组对应位置 shopsList[i, m] = Convert.ToDouble(profitStrs[m]); } } // 寻找最盈利的季度和店铺 double maxProfit = double.MinValue; int bestShopIndex = 0; int bestTrimesterIndex = 0; for (int i = 0; i < numberOfShops; i++) { for (int m = 0; m < numberOfTrimesters; m++) { if (shopsList[i, m] > maxProfit) { maxProfit = shopsList[i, m]; bestShopIndex = i; bestTrimesterIndex = m; } } } // 输出结果(注意店铺和季度是从1开始计数) Console.WriteLine($"最盈利的是第{bestShopIndex + 1}家店铺的第{bestTrimesterIndex + 1}季度,利润为{maxProfit:F2}"); } }
代码说明
- 填充数组部分:每个店铺输入后,拆分字符串直接遍历4个季度,把对应的值赋值到
shopsList[i, m],i是当前店铺,m是当前季度,逻辑清晰且不会出错。 - 寻找最大值部分:遍历整个二维数组,记录最大利润的位置,最后输出的时候记得把索引加1(因为用户输入的第一家是索引0,对应实际的第1家),用
{maxProfit:F2}保证输出保留两位小数。
内容的提问来源于stack exchange,提问作者Catalin Urcan
相关产品推荐
相关产品推荐

