用20个矩形填充一个数组,每个矩形的长度和宽度都是随机的
本文关键字:随机 数组 填充 20个 一个 | 更新日期: 2023-09-27 18:28:38
-
创建矩形(大小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数组。
您可以使用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();
}
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?
这不是你在这里需要做的。您想要创建一个已知大小的一维矩形数组。创建空数组,然后循环遍历并填充。