You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在二维数组中显示指定行?仅用嵌套FOR循环实现

如何用嵌套FOR循环显示二维数组的指定行

你现在的问题是输入指定行索引后,代码却输出了整个二维数组的所有元素,核心原因是你输入的行索引变量r被后面的for循环覆盖了——原本你通过Console.ReadLine()获取了用户想要查看的行号,但紧接着的for (r = 0; r < 5; r++)直接把r重新赋值为0,然后循环遍历所有5行,自然会输出所有内容。

只要去掉遍历所有行的外层循环,直接用用户输入的r来定位目标行,再用内层循环遍历该行的所有列就行,完全符合你要求的基础嵌套FOR循环写法:

int[,] numbers = new int[5, 10] {
    {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
    {11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
    {21, 22, 23, 24, 25, 26, 27, 28, 29, 30},
    {31, 32, 33, 34, 35, 36, 37, 38, 39, 40},
    {41, 42, 43, 44, 45, 46, 47, 48, 49, 50}
};

Console.WriteLine("Enter row index between 0 - 4: ");
int r = Convert.ToInt32(Console.ReadLine());

// 只处理用户指定的行,不需要遍历所有行
Console.WriteLine($"Numbers in row {r}");
for (int c = 0; c < 10; c++)
{
    Console.WriteLine(numbers[r, c]);
}

如果一定要保留嵌套循环的结构(比如练习嵌套写法),可以把外层循环改成只执行一次,锁定用户输入的行:

// 外层循环只循环指定的那一行
for (int row = r; row == r; row++)
{
    Console.WriteLine($"Numbers in row {row}");
    for (int c = 0; c < 10; c++)
    {
        Console.WriteLine(numbers[row, c]);
    }
}

这样修改后,当你输入行索引2,就只会输出第3行(索引从0开始)的21到30这些数字了。

内容的提问来源于stack exchange,提问作者Aguni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 18:42:24