我的老师用帕斯卡的三角形为我的问题写了一个测试员课。这是:
public class TestTriangle
{
public static void main(String args[])
{
PascalsTriangle triangle = new PascalsTriangle(7);
if (triangle.getElement(5,2)==10)
System.out.println("Triangle has passed one test.");
else
System.out.println("Triangle is wrong.");
triangle.showTriangle();
}
}
这是我的代码:
public class PascalsTriangle
{
private int rows;
private int column;
private int position;
/**
* Constructor for objects of class PascalsTriangle
*/
public PascalsTriangle()
{
rows = 2;
}
public PascalsTriangle(int n)
{
rows = n;
}
public int getElement(int n, int k)
{
rows = n;
column = k;
//now the equation
int z;
int y;
int d;
for (z = 1; z <= n; z++) //z is n! at nominator of equation
{
int a = z;
z = z*n;
z = a+z;
}
for (y = 1; y <= k; y++) //y is k! at denominator of equation
{
int b = y;
y = y*k;
y = b+y;
}
int c = n-k;
for (d = 1; d <= c; d++) //d is (n-k)! at denominator of equation
{
{
int e = d;
d = d*c;
d = e+d;
}
}
position = z/(y*d);
return position;
}
public showTriangle() //outputs entire triangle
{
}
}
我唯一的问题是使用showTriangle方法。我不知道如何把它整个三角形。 如果我唯一的公式是找到一个特定的位置,我将如何打印整个三角形?
答案 0 :(得分:0)
我编译了你的代码。 Java强迫我为showTriangle()
声明一个返回类型。我选择了无效:
public void showTriangle()
{
}
我跑了测试
triangle.getElement(5,2)==10
打印程序
三角形错了。
您确定getElement
方法返回正确的结果吗?我打印了getElement(5,2)
的结果,得到了0
。
一旦getElement函数工作,我将使用两个循环实现showTriangle()方法。在伪代码中,它看起来像这样。行号(n)的一个循环和列(k)的一个循环
for i = 0 to n
{
for j = 0 to k
{
System.out.print(getElement(i,j) + " ") //Print triangle value and a space
}
System.out.print("\n") //Skip down one line
}
//NOTE: You have to pick the right value of k based on the n.
这不会打印格式精美的三角形,但如果getElement()
正常工作,则应打印一些内容:
1
1 1
1 2 1