如何在控制台中用它的对角线绘制一个空心矩形

时间:2015-11-14 12:04:00

标签: c# console

我想用它的对角线绘制一个空心矩形。矩形的高度应该大于5且最多为20. witdh也应该大于5且最多为80.我已经得到了这段代码:

Class<?> clazzA = ClassA.class;
ClassA objectA = new ClassA();
Method method = clazzA.getMethod(methodName, parasType);
method.setAccessible(true);
method.invoke(objectA,paras);
Field field = clazzA.getField(fieldName);
field.setAccessible(true);
Object fieldType = field.get(objectA);

但是此代码仅适用于正方形。对于矩形,它不能正确绘制对角线。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

当矩形不是正方形时,您必须考虑宽度和高度之间的比率。你可以这样做:

using System;

public class Test
{
    static int width;
    static int height;

    public static void Main()
    {
        Console.Write("Enter width of rectangle: ");
        width = int.Parse(Console.ReadLine()); 
        Console.Write("Enter height of rectangle: ");
        height = int.Parse(Console.ReadLine()); 
        Console.WriteLine();
        if(width > 5 && width <= 80 && height > 5 && height <= 20)
        {
            draw();
        }
        else
        {
            Console.WriteLine("Invalid entry!");
        }
    }

    static void draw()
    {
        Console.WriteLine((float)width/(float)height);
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                if (IsBorder(x, y)  || IsDiagonal(x, y))
                {
                    Console.Write("*");
                }
                else
                {
                    Console.Write(" ");
               }

            } Console.WriteLine();
        }
    }

    static bool IsBorder(int x, int y)
    {
        return x == 0 
            || y == 0  
            || x == width - 1  
            || y == height - 1;
    }

    static bool IsDiagonal(int x, int y)
    {
        return width < height  
            ? IsDiagonalHigh(x, y)  
            : IsDiagonalWide(x,y);
    }

    static bool IsDiagonalHigh(int x, int y)
    {
        var aspectRatio = (float)width / (float)height;
        return x == (int)(y * aspectRatio) 
            || x == width - (int)(y * aspectRatio) - 1;
    }

    static bool IsDiagonalWide(int x, int y)
    {
        var aspectRatio = (float)height / (float)width;
        return y == (int)(x * aspectRatio)  
            || y == (int)((width - x - 1) * aspectRatio);
    }

}

如您所见,我冒昧地将wh更改为静态字段widthheight