如果我有1到100位数,我应该得到输出
1--100
2--99
3--98
.
..
..
49---50
Run Code Online (Sandbox Code Playgroud)
代码低于其给定索引的范围,数组不需要很多维度
static void Main(string[] args)
{
//// A. 2D array of strings.
string[][] a = new string[100][];
int bound0 = a.GetUpperBound(0);
int bound1 = a.GetUpperBound(1);
for (int i = 0; i <= bound0; i++)
{
for (int x = 100; x <= bound1; x--)
{
string s1 = a[i][x];
Console.WriteLine(s1);
}
}
Console.WriteLine();
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)
您需要为数组提供第二个维度.在内部循环中,您将递减loop变量而不是递增,这也会导致超出范围的异常.您可能需要知道锯齿状和二维数组之间的区别.该职位将解释这一点.这个语句int bound1 = a.GetUpperBound(1); 由于尚未声明第二个维度,因此给出了异常.
使用锯齿状数组.
string[][] a = new string[100][];
int bound0 = a.GetUpperBound(0);
for(int i = 0; i <= bound0; i++)
a[i] = new string[3];
for (int i = 0; i <= bound0; i++)
{
int bound1 = a[i].GetUpperBound(0);
for (int x = 0; x <= bound1; x++)
{
a[i][x] = (i + x).ToString();
string s1 = a[i][x];
Console.WriteLine(s1);
}
}
Run Code Online (Sandbox Code Playgroud)
使用二维数组.
string[,] a = new string[100,4];
int bound0 = a.GetUpperBound(0);
int bound1 = a.GetUpperBound(1);
for (int i = 0; i < bound0; i++)
{
for (int x = 0; x < bound1; x++)
{
a[i,x] = (i+x).ToString();
string s1 = a[i,x];
Console.WriteLine(s1);
}
}
Console.WriteLine();
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)
根据更新进行编辑
string[][] a = new string[100][];
int bound0 = a.GetUpperBound(0);
for(int i = 0; i <= bound0; i++)
a[i] = new string[100];
for (int i = 0; i <= bound0; i++)
{
int bound1 = a[i].GetUpperBound(0);
for (int x = bound1; x >= 0; x--)
{
a[i][x] = (i+1).ToString() +"--"+ (x+1).ToString();
string s1 = a[i][x];
Console.WriteLine(s1);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
733 次 |
| 最近记录: |