【发布时间】:2014-10-31 00:19:37
【问题描述】:
创建一个矩形数组(大小为 20)
用 20 个矩形填充数组,每个矩形的长度和宽度都是随机的。然后打印数组的内容。
这是我给定的矩形类:
class Rectangle
{
private int length, width;
private int area, perimeter;
public Rectangle()
{
}
public Rectangle(int l, int w)
{
length = l;
width = w;
}
public void SetDimension(int l, int w)
{
length = l;
width = w;
}
public void InputRect()
{
length = int.Parse(Console.ReadLine());
width = int.Parse(Console.ReadLine());
}
public void ComputeArea()
{
area = length * width;
}
public void ComputePerimeter()
{
perimeter = 2 * (length + width);
}
public void Display()
{
Console.WriteLine("Length: {0} \tWidth: {1} \tArea: {2} \tPerimeter: {3}", length, width, area, perimeter);
}
}
这是我获取随机数的程序的开始。我被困在这里了。
如何将 2 个数字准确地输入到数组的同一索引中?
class Program
{
static void Main(string[] args)
{
Rectangle r1 = new Rectangle();
int[] x = new int[20];
Random rand = new Random();
for (int i = 0; i < x.Length; i++)
{
int width = rand.Next(45, 55);
int length = rand.Next(25, 35);
}
//r1.InputRect(width, length);
Console.WriteLine("The following rectanglesn are created: ");
//r1.Display(x);
}
}
【问题讨论】:
-
为什么要使用 int 数组?为什么不创建一个矩形数组
Rectangle[] rectangles = new Rectangle[20]然后在 for 循环的每个步骤中使用new Rectangle(rand.Next(45,55), rand.Next(25,35)将其归档? -
如果下面提供的任何答案帮助您解决了问题,请用检查标记答案