打印帕斯卡三角(递归)(JAVA) [英] Printing Pascals Triangle (recursive) (JAVA)
本文介绍了打印帕斯卡三角(递归)(JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
到目前为止,我已经知道了,但是我不太确定printPTriangle如何使用代码来打印三角形.如果有人可以帮我解决这个问题,我将不胜感激.
So far I have this, but I am not quite sure how printPTriangle can print the triangle using the code. If someone could help me out with this, I would be grateful.
public static int factorial(int n) {
if (n == 1) {
return 1;
}
return n * (factorial(n - 1));
}
public static int pascalsNumber(int x, int y) {
return factorial(x)/(factorial(y) * factorial((x - y))); //Using combinations formula
}
public static void printPTriangle(int z) {
}
推荐答案
尝试一下,
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
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();
}
}
}
请注意上面用于创建格式正确的三角形的格式命令. %4d指示格式化程序在4个空格内打印数字.
Note the formatting commands used above to create a nicely formatted triangle. %4d instructs the formatter to print the number within 4 spaces.
这篇关于打印帕斯卡三角(递归)(JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文