【发布时间】:2017-05-02 00:32:58
【问题描述】:
我的问题最近被搁置了,所以我决定再问一次。
我的教授希望我们在 Java 上制作帕斯卡三角形。他为我们提供了一个完整的 Main 类,它应该可以工作,我们必须使用它。我们不必编辑 Main 类。 Main 类是正确的。它需要我们必须在代码中编写的方法。另外,我提供了正确的输出和 Pascal 类的模板,其中包含我应该填写的方法。
这里是主类:
public class Main
{
public static void main(String[] args)
{
int n = args.length == 1 ? Integer.parseInt(args[0]) : 1;
for (int i = 1; i <= n; ++i)
{
int[] arr = Pascal.triangle(i);
System.out.print((i < 10 ? " " : "") + i + ": ");
for (int j : arr)
{
System.out.print(j + " ");
}
System.out.println();
}
}
}
我的教授希望我们使用他的 Pascal 类模板,我们只需要在代码中编写三角形方法。这是我们必须为分配编写代码的唯一区域。
public class Pascal
{
public static int[] triangle(int n)
{
//My code goes here
return new int[]{0};
}
}
输出应该是这样的:
1: 1
2: 1 1
3: 1 2 1
4: 1 3 3 1
5: 1 4 6 4 1
6: 1 5 10 10 5 1
7: 1 6 15 20 15 6 1
8: 1 7 21 35 35 21 7 1
9: 1 8 28 56 70 56 28 8 1
10: 1 9 36 84 126 126 84 36 9 1
这是我的 Pascal 类代码:
public class Pascal
{
public static int[] triangle(int n)
{
int [][] pt = new int[n+1][];
for (int i = 0; i < n; i++)
{
pt[i] = new int[i + 1];
pt[i][0] = 1;//sets the position to 1
pt[i][i] = 1;
for (int j = 1; j < pt[i].length - 1; j++)
{
pt[i][j] = pt[i-1][j-1] + pt[i-1][j];
}
}
return new int[]{0};
}
}
我的输出:
1: 0
1: 10
1: 20
1: 1
1: 0
1: 0
【问题讨论】:
-
你的 pascal.triangle 方法总是返回一个空数组??
-
好吧,我不知道它是否为空,因为它返回的数组包含不应该返回的奇怪数字。
标签: java arrays pascals-triangle