2015-11-14 39 views
0

我想用對角線繪製空心矩形。矩形的高度應大於5,最多20 witdh也應該是大於5,最多80我已經得到這個代碼:如何在控制檯中用對角線繪製空心矩形

using System; 

public class Test 
{ 
    public static void Main() 
    { 
     Console.Write("Enter width of rectangle: "); 
     int w = int.Parse(Console.ReadLine()); 
     Console.Write("Enter height of rectangle: "); 
     int h = int.Parse(Console.ReadLine()); 
     Console.WriteLine(); 
     if(w > 5 && w <= 80 && h > 5 && h <= 20) 
     { 

      draw(w, h); 
     } 
     else 
     { 
      Console.WriteLine("Invalid entry!"); 
     } 
    } 
    static void draw(int w, int h) 
    { 
     for (int i = 0; i < h; i++) 
     { 
      for (int j = 0; j < w; j++) 
      { 
       if ((i == 0) || (j == 0) || (i == h - 1) || (j == w - 1) || (i == j) || (i + j == w - 1)) 
       { 
        Console.Write("*"); 
       } 
       else 
       { 
        Console.Write(" "); 
       } 

      } Console.WriteLine(); 
     } 
    } 
} 

但這個代碼繪製正確只爲正方形。對於矩形,它不會正確繪製對角線。任何幫助將不勝感激。

回答

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

+0

它似乎工作,謝謝。 – fsacer

+0

您是否願意爲初學者級別的程序員解釋更深入的解決方案?對我來說,IsDiagonalHigh和IsDiagonalWide的工作原理可能更具圖形性,因爲我必須向教授解釋它。這個解決方案的工作方式是每次將矩形分成4個相等的部分,並確定繪製恆星的座標? – fsacer