gpt4 book ai didi

c# - GetLength() 方法在数组上无法按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:28 25 4
gpt4 key购买 nike

这是一段 C# 代码。

它输出以下文本:

tab.Length = 6
tab.Rank = 2
Length of dim 0 of tab : 0
Length of dim 1 of tab : 1

我期待以下文字:

tab.Length = 6
tab.Rank = 2
Length of dim 0 of tab : 2
Length of dim 1 of tab : 3

为什么不呢?谢谢。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TableTest
{
class Program
{
static void Main(string[] args)
{
int[,] tab = new int[2, 3];

for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
tab[i, j] = 2 * i + j;
}
}
Console.WriteLine("tab.Length = {0}", tab.Length);
Console.WriteLine("tab.Rank = {0}", tab.Rank);
for (int i = 0; i < tab.Rank; i++)
{
Console.WriteLine("Length of dim {0} of tab : {0} ", i, tab.GetLength(i));
}

}
}
}

最佳答案

大胆猜测:你最后的格式字符串是错误的:

Console.WriteLine("Length of dim {0} of tab: {0} ", i, tab.GetLength(i));

您使用了两次 {0},因此您在两个占位符中输出了 i 的值。

改用这个:

Console.WriteLine("Length of dim {0} of tab: {1} ", i, tab.GetLength(i));

关于c# - GetLength() 方法在数组上无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11634543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com