回 帖 发 新 帖 刷新版面

主题:求助一到程序题

我要打印出这样的图象
                               1
                           1   2   1  
                        1  2   4   2   1
                     1  2  4   8   4   2   1
                  1  2  4  8   16  8   4   2   1
               1  2  4  8  16  32  16  8   4   2   1
            1  2  4  8  16 32  64  32  16  8   4   2   1 
         1  2  4  8  16 32 64  128 64  32  16  8   4   2   1 
 


我写的程序是这样的的 
import javax.swing.JOptionPane;
public class tuan {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
for(int row=1;row<=8;row++){
    for(int i=1;i<=(8-row)*3;i++)
        System.out.print(" ");
    for(int j=1;j<=row*3;j++){
        int num=(int)Math.pow(2,j-1);
        System.out.printf("%3d",num);
    }
    for(int k=1;k<=row-1;k++){
        int m=(int)Math.pow(2,row-k-1);
        System.out.printf("%3d",m);
    }
    System.out.println();
}
    }

}

可是运行结果不对.

回复列表 (共4个回复)

沙发

你写的是java 程序吗呵呵
怎么还有c语言的东西 能编译吗???

板凳

这样的我看是你的算法的逻辑上的问题,
数学好就没问题
自己好好在纸上理解理解

3 楼

做个参考,最好自己写个

public class Tuan {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        /*for (int row = 1; row <= 8; row++) {
            for (int i = 1; i <= (8 - row) * 3; i++)
                System.out.print(" ");
            for (int j = 1; j <= row * 3; j++) {
                int num = (int) Math.pow(2, j - 1);
                System.out.printf("%3d", num);
            }
            for (int k = 1; k <= row - 1; k++) {
                int m = (int) Math.pow(2, row - k - 1);
                System.out.printf("%3d", m);
            }
            System.out.println();
        }*/
        Integer row = 8;
        write(row);
    }
    public static void write(Integer row){
        for(int i = 0;i < row ;i++){
            
            //打印前段空格
            for(int j = 0; j< row - i ; j++){
                System.out.print ("  ");
            }
            
            if(i == 0){
                System.out.print((int)Math.pow(2, i));
                System.out.println();
                continue;
            }
            
            //打印前半数字
            int k = 0 ;
            for( ; k < i ; k++){
                System.out.print((int)Math.pow(2, k));
                System.out.print(" ");
            }
            //打印后半数字
            if(k != 0){
                for(;k >= 0;k--){
                    System.out.print((int)Math.pow(2, k));
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}

4 楼

把第二个for
 for(int j=1;j<=row*3;j++){  //修改这一行
        int num=(int)Math.pow(2,j-1);
        System.out.printf("%3d",num);
    }
改为
for(int j=1;j<=row;j++){  //修改这一行
        int num=(int)Math.pow(2,j-1);
        System.out.printf("%3d",num);
    }
就可以了。

还有就是你用的全是C语法哦:(

我来回复

您尚未登录,请登录后再回复。点此登录或注册