繁体   English   中英

Java中的三角形模式

[英]Triangle pattern in Java

我正在用特定的数字模式在 Java 中创建一个三角形。 我在想出一个数学方程时遇到问题,该方程在用户输入行数后输出这些数字/模式:
看图片

我的代码工作正常,但数字不正确。 有谁知道该模式的等式?

我的代码:

import java.util.Scanner;
public class Triangle {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        System.out.println("Enter the number of lines: ");
        int rows = input.nextInt();

        for(int i =0;i<rows;i++) {
            int number = 1;
            System.out.format("%"+(rows-i)*2+"s","");
            for(int j=0;j<=i;j++) {
                System.out.format("%4d",number);
                number = number * (i - j) / (j + 1);

            }
            System.out.println();
        }
    }
}

正如Andreas的评论中所提到的,2 个 for 循环可以很好地工作:

import java.util.Scanner;

public class Triangle {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        System.out.println("Enter the number of lines: ");
        int rows = input.nextInt();

        for(int i =0;i<rows;i++) {
            System.out.format("%"+4*(rows-i+1)+"s","");
            for(int j=i+1; j>1; j--)
                System.out.format("%4d", j);
            for(int j=1; j<=i+1; j++)
                System.out.format("%4d", j);

            System.out.println();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM