创建一个Rectangle数组(大小为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);
}
}
答案 0 :(得分:3)
您应该创建一个Rectangles数组,而不是一个int数组。
答案 1 :(得分:2)
您可以使用多维数组int执行List<Rectangle>
或Rect[] m_Rects = new Rect[20];
。看起来有点像家庭作业;)
一个简单的解决方案是:
Random rand = new Random();
Rectangle[] ra = new Rectangle[20];
for (int i = 0; i < ra .Length; i++)
{
int length = rand.Next(25, 35);
int width = rand.Next(45, 55);
ra[i] = new Rectangle(length, width);
}
Console.WriteLine("The following rectangles are created: ");
foreach(Rect r in ra)
{
r.Display();
}
答案 2 :(得分:1)
Rectangle[] rects = new Rectangle[20];
Random rand = new Random();
for (int i = 0; i < rects.Length; i++)
{
int width = rand.Next(45, 55);
int length = rand.Next(25, 35);
rects[i] = new Rectangle(length,width);
}
How exactly would I enter 2 numbers into the same index of an array?
这不是你需要做的。您想要创建具有已知大小的一维矩形阵列。创建空数组,然后遍历它并填充它。