0

我正在尝试使我制作的三角形面朝下。尝试了很多次,但我不知道如何做到这一点。

我知道的代码是:

public static void drawPyramide(int lines, char symbol, boolean startDown) {
    //TRIANGLE

    if(startDown) {
                //The triangle up side down should be here. 
            }

    else {
        int c = 1;
        for (int i = 0; i < lines; i++) {
            for (int j = i; j < lines; j++) {
                System.out.print(" ");
            }
            for (int k = 1; k <= c; k++) {
                if (k%2==0) System.out.print(" ");

                else System.out.print(symbol);
            }

        System.out.print("\n");
        c += 2;
        }
    }

}

有什么建议我可以“翻转”这个三角形吗?谢谢。

4

3 回答 3

1

要翻转三角形,你真的只需要改变迭代的方向。而不是从i = 0i < lines你需要从到下i = lines-1i >= 0

您还需要将 更改c为要从多少个空格和符号开始。

可能看起来像这样:

int c = 2*lines;
for (int i = lines-1; i>=0; i--)
{
    for (int j = i; j < lines; j++)
    {
        System.out.print(" ");
    }
    for (int k = 1; k <= c; k++)
    {
        if (k % 2 == 0)
        {
            System.out.print(" ");
        }
        else
        {
            System.out.print(symbol);
        }
    }

    System.out.print("\n");
    c -= 2;
}
于 2012-10-25T13:16:56.353 回答
0

反转第一个循环条件,即从行数开始并减少它。也相应地调整你c,让它从高到低,例如下面:

    int c = 2*lines-1;
    for (int i = lines; i > 0; i--) {
        for (int j = i; j < lines; j++) {
            System.out.print(" ");
        }
        for (int k = 1; k <= c; k++) {
            if (k%2==0) System.out.print(" ");

            else System.out.print(symbol);
        }

      System.out.print("\n");
      c -= 2;
    }
于 2012-10-25T13:18:55.290 回答
0
import java.util.Scanner;

public class EquilateralTraingle {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int side = sc.nextInt();
        constructEquTri(side);

    }

    private static void constructEquTri(int length) {
        // loop for each line
        for (int i = length; i > 0; i--) {
            // loop for initial spaces in each line
            for (int k = 0; k < length - i; k++) {
                System.out.print(" ");
            }
            // loop for printing * in each line
            for (int j = 0; j < i; j++) {

                System.out.print("*");
                System.out.print(" ");

            }
            System.out.println();
        }
    }

}
/*Output:
    10
    * * * * * * * * * * 
     * * * * * * * * * 
      * * * * * * * * 
       * * * * * * * 
        * * * * * * 
         * * * * * 
          * * * * 
           * * * 
            * * 
             * 
*/
于 2018-03-13T05:41:53.983 回答