【问题标题】:Fill in a array with 20 rectangles, each has random length and width用 20 个矩形填充一个数组,每个矩形的长度和宽度都是随机的
【发布时间】:2014-10-31 00:19:37
【问题描述】:
  1. 创建一个矩形数组(大小为 20)

  2. 用 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) 将其归档?
  • 如果下面提供的任何答案帮助您解决了问题,请用检查标记答案

标签: c# arrays


【解决方案1】:

您应该创建一个矩形数组,而不是整数数组。

【讨论】:

  • 是的,或者使用两个数组,一个是宽度,一个是长度 - 但我们都知道这是个坏主意:)
【解决方案2】:

您可以使用多维 int 数组来执行 List&lt;Rectangle&gt;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();
}

【讨论】:

  • 由于他没有要求我们为他编写整个代码,我认为在做作业时寻求帮助没有任何问题;)
  • 你是对的。我只是看起来像一些典型的家庭作业;)
  • 是的,我也是这么想的 :D
【解决方案3】:
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?

这不是你需要在这里做的。您想要创建一个已知大小的一维矩形数组。创建空数组,然后循环遍历并填充它。

【讨论】:

    猜你喜欢
    • 2022-10-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多