2

我的老师为他的帕斯卡三角形问题写了一个测试课程。这里是:

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方法。我不知道如何让它输出整个三角形。如果我拥有的唯一公式是查找特定位置,我将如何打印出整个三角形?

4

1 回答 1

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 
于 2015-01-20T19:38:50.897 回答