首页 > 解决方案 > 使用二维数组和嵌套循环打印几何序列表

问题描述

我是编程新手,我需要帮助。因此,我的程序需要使用二维数组以表格格式打印几何序列。但我也很清楚我缺少生成所需输出的代码行(而且我不知道要添加什么):

      1 2  4  8 16 32 64 128 256 512
      2 4  8 16 32 64...
      4 8 16...
      8... 
     16...
     32...    
     64... 
    128...
    256...
    512...

这是我到目前为止得到的:

    int [][] array = new int[10][10];
    array[0][0] = 1;
    
    for(int i = 0; i < array.length; i++) { 
        for(int j = 0; j < array[i].length; j++) {
            array[i][j] = (i+i) + (j+j);
        }   
    }

    for(int i = 0; i < array.length; i++) { 
        for(int j = 0; j < array[i].length; j++) {
            System.out.print(array[i][j] + " ");
        } 
    System.out.println();   
    }

我已经搜索了一些相关的程序和问题,但它们都没有帮助我。无论如何,如果有人回应,非常感谢你!

标签: javaarraysnested-loops

解决方案


一个解决方案可以是(在第一个循环中):

array[i][j] = (int)Math.pow(2,i)*(int)Math.pow(2,j);

基础开始于1并且2 at power i在每一行上。只需乘以2 at corresponding power(j,每行元素)。

[0_i,0_j]=base*next=2^0*2^0=1*1

[1,2]=2^1*2^2=2*4=8, ETC


推荐阅读