簡體   English   中英

如何在 JAVA 中使用循環打印此數字模式?

[英]How to print this number pattern using loops in JAVA?

如何打印此模式,修改我的原始代碼如下:

我是 Java 初學者,無法創建下面列出的模式。

圖案:

1
1 ,1
1 ,2 ,1
1 ,3 ,3 ,1
1 , 4 , 6 , 4 , 1
1 , 5 , 1 0 , 1 0 , 5 , 1

我的代碼:

public class Q2 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int count = 5;
        for (int i = 1; i <= count; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(i);
            }
            System.out.println();
        }
    }
}

我的輸出:

1
22
333
4444
55555

我希望我可以發表評論,但我沒有足夠的聲譽。

例如,您需要在 Yimin 的答案中添加一些內容來計算階乘。

static int factorial(int n){    
    if (n == 0)    
        return 1;    
    else    
        return(n * factorial(n-1));
}

你想要的是i choose j為每個術語i choose j 這是通過公式:

i!/(j!*(i-j)!)
public static void main(String[] args) {
    int count = 5;
    for (int i = 0; i <= count; i++) {
        for (int j = 0; j <= i; j++) {
            System.out.print(factorial(i) / (factorial(j) * factorial(i - j)));
            System.out.print(' ');
        }
        System.out.println();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM