星号矩形中的对角线

时间:2015-12-03 00:01:57

标签: c# algorithm

我试图用对角线打印一个矩形的星号。

我有代码,但我想知道是否有办法让它更加对称?

        int height = int.Parse(Console.ReadLine());
        int width = int.Parse(Console.ReadLine());

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (i == 0 || j == 0 || i == height - 1 || j == width - 1 || i == j || i + j == width- 1) {
                    Console.Write("*");
                }
                else {
                    Console.Write(" ");
                }

            }
            Console.WriteLine();
        }

随着(12,16)的影响,它出来了:

****************
**            **
* *          * *
*  *        *  *
*   *      *   *
*    *    *    *
*     *  *     *
*      **      *
*      **      *
*     *  *     *
*    *    *    *
****************

1 个答案:

答案 0 :(得分:1)

height * width矩形中绘制对角线:

    int height = int.Parse(Console.ReadLine());
    int width = int.Parse(Console.ReadLine());

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            // Calculate the slope
            int x = (int) (0.5 + (1.0 * (i) * width) / (height-0.5));
            if (i == 0 || j == 0 || i == height - 1 || j == width - 1 || x == j || j == width - x - 1) {
                Console.Write("*");
            }
            else {
                Console.Write(" ");
            }

        }
        Console.WriteLine();
    }