0

我一直在为作业做帕斯卡三角形,并且我已经获得了以我想要的方式打印三角形广告的整个代码。我们的老师要求我们在每一行显示该行内数字相乘的结果;例如:在第 1 行它应该打印 1,在第 2 行打印 1,在第 3 行打印 2,在第 4 行打印 9 等等......似乎有效,在这里我把我的代码留给你,这样你就可以检查一下,看看你是否可以帮助我。顺便说一下,计数器数组是 c[] 。非常感谢!

import javax.swing.*;
import java.util.*;
public class class1_080414_Rodrigo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String fila;
        int f, a=0, b=0;
        //
        fila=JOptionPane.showInputDialog(null, "Until which line of the triangle would you like to prnt?");
        f=Integer.parseInt(fila);
        //
        if (f<0){
            JOptionPane.showMessageDialog (null, "You cannot type negative numbers.");
        }
        int triangulo [][] = new int[f][f];
        int c [] = new int [f];
        //
        for (a=0;a<f;a++){
            for (b=0; b<f; b++){
                triangulo[a][b] = 0;
            }
        }
        for (a=0;a<f;a++){
            triangulo[a][0] = 1;
        }
        for (a=1;a<f;a++) {
            for (b=1;b<f;b++) {
                triangulo[a][b] = triangulo[a-1][b-1] + triangulo[a-1][b];
            }
        } 
        for (a=0;a<f;a++) {
            for(b=0;b<=a;b++) {
                if (b==0){
                    System.out.format("%"+(80-a)+"s", "");
                }
                c[a]=1;
                c[a]=c[a]*triangulo[a][b];
                System.out.print(triangulo[a][b]+" ");
            }
            System.out.print(" ="+c[a]);
            System.out.println();
        }
    }
}
4

1 回答 1

0

您不断将 c[a] 重置为 1。这应该来自 b 循环。

改变

        for (a=0;a<f;a++) {
        for(b=0;b<=a;b++) {
            if (b==0){
                System.out.format("%"+(80-a)+"s", "");
            }
            c[a]=1;
            c[a]=c[a]*triangulo[a][b];
            System.out.print(triangulo[a][b]+" ");
        }
        System.out.print(" ="+c[a]);
        System.out.println();
    }

    for (a=0;a<f;a++) {
        c[a]=1;
        for(b=0;b<=a;b++) {
            if (b==0){
                System.out.format("%"+(80-a)+"s", "");
            }
            c[a]=c[a]*triangulo[a][b];
            System.out.print(triangulo[a][b]+" ");
        }
        System.out.print(" ="+c[a]);
        System.out.println();
    }
于 2014-04-15T17:26:34.863 回答