【发布时间】:2016-02-25 00:51:24
【问题描述】:
我有一个程序最终可以打印帕斯卡的三角形,有点。 无论出于何种原因,当它打印时,它会按照您的假设正确打印所有行,但是在每一行的末尾它应该只停在一个位置,最后一整行被粘贴。我举个例子。 而不仅仅是这个:
Enter the row number up to which Pascal's triangle has to be printed: 4
Rows to print: 4
1
11
121
1331
14641
它打印这个:
Enter the row number up to which Pascal's triangle has to be printed: 4
Rows to print: 4
1
11
1211
1331211
14641331211
最后那些额外的花絮不应该在那里。我不知道为什么会有。非常感谢任何帮助。
“是的,它应该使用递归,不,我不能改变它。”
这是我的代码:
import java.util.Scanner;
public class pascalsTriangle {
public static int rows;
public static String list = "";
public static String line = "1";
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the row number up to which Pascal's triangle has to be printed: ");
rows = scan.nextInt();
System.out.println("Rows to print: " + rows);
scan.close();
if (rows == 1)
System.out.println("1");
else {
System.out.println(print(1, rows));
}
}
public static String print(int largest, int row) {
if (row < 1)
return "1";
else{
list = print(1, row - 1) + "\n" + curLine(row, 0, 1);
}
return list;
}
public static String curLine(int n, int k, int last) {
if(n > k && n != 0){
line = Integer.toString(last) + curLine(n, k + 1, last*(n - k)/(k + 1));
}
return line;
}
}
【问题讨论】:
标签: java recursion pascals-triangle