C#-创建一个二维数组,然后在其中循环
我试图编写这样的代码:创建一个多维数组,然后循环遍历所有行和列,并在该单元格中放置一个介于0到9之间的随机数 例如,如果我打印出方框/矩形,它会像这样:C#-创建一个二维数组,然后在其中循环,c#,arrays,multidimensional-array,C#,Arrays,Multidimensional Array,我试图编写这样的代码:创建一个多维数组,然后循环遍历所有行和列,并在该单元格中放置一个介于0到9之间的随机数 例如,如果我打印出方框/矩形,它会像这样: 1 4 6 2 4 1 4 5 6 9 2 1 0 2 3 4 5 9 2 5 6 1 9 4 3 6 7 2 4 6 7 2 2 4 1 4 我拥有的代码(我相信)可以正常工作,但是,只有当我创建具有相同行数和列数(例如10x10、20x20、15x15)的数组时,它才能工作,但是如果我尝试类似30x10的东西,我会得到: Unhandle
1 4 6 2 4 1
4 5 6 9 2 1
0 2 3 4 5 9
2 5 6 1 9 4
3 6 7 2 4 6
7 2 2 4 1 4
我拥有的代码(我相信)可以正常工作,但是,只有当我创建具有相同行数和列数(例如10x10、20x20、15x15)的数组时,它才能工作,但是如果我尝试类似30x10的东西,我会得到:
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the boun
ds of the array.
at ConsoleApplication2.Program.Main(String[] args) in c:\Users\Lloyd\Document
s\Visual Studio 2010\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs
:line 22
基本上,我不知道如何创建具有不同行数和列数的数组,然后在其中循环
任何线索都将不胜感激,谢谢
我的代码:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
//The width and height of the box.
const int row = 30;
const int column = 10;
static void Main(string[] args)
{
int[,] array = new int[row, column];
Random rand = new Random();
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
array[i, j] = rand.Next(0, 10);
}
}
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
Console.Write(array[i, j].ToString() + " ");
}
Console.WriteLine("");
}
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统文本;
命名空间控制台应用程序2
{
班级计划
{
//盒子的宽度和高度。
const int row=30;
const int column=10;
静态void Main(字符串[]参数)
{
int[,]数组=新的int[行,列];
Random rand=新的Random();
对于(int i=0;i
您的for
循环已反转:
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
array[i, j] = rand.Next(0, 10);
}
}
for(int i=0;i|
您已在循环中反转。您分配了30行和10列,但循环执行
10行30列
试试这个
int[,] array = new int[row, column];
Random rand = new Random();
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
array[i, j] = rand.Next(0, 10);
}
}
int[,]数组=新的int[行,列];
Random rand=新的Random();
对于(int i=0;i|
我相信在初始化数组时,您已经交换了行索引和列索引。
换衣服
int[,] array = new int[row, column];
到
在for循环中交换行和列
int[,] array = new int[column, row];