使用Java每行每行打印10位数字

时间:2018-07-13 04:04:19

标签: java loops for-loop printing

如何每行/行打印10个数字?我想要这样的输出:

1 2 3 3 4 5 6 7 8 9 10
1 4 9 16 25 36 49 64 81 100
1 8 27 64 125 216 343 512 729 1000
................
...................

但是我现在所得到的是混乱的。

1 1 1 1 1 2 4 8 16 32 3 9 27 81 243 4 16 64 256 1024 5 25 125 625 3125 6 36 216 1296 7776 7 49 343 2401 16807 8 64 512 4096 32768 9 81 729 6561 59049 10 100 1000 10000 100000

这是代码段

public class NumberOnly
{
    public static void main (String [] args)
    {
        for(int count = 1; count <= 10; count++) {

                 System.out.print(count + " ");
                 System.out.print((int) Math.round(Math.pow(count, 2))  + " ");
                 System.out.print((int) Math.round(Math.pow(count, 3))  + " ");
                 System.out.print((int) Math.round(Math.pow(count, 4))  + " ");
                 System.out.print((int) Math.round(Math.pow(count, 5))  + " ");
        }
    }
}

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

在这里,尝试此代码。可以按照您想要的方式工作。

public class NumberOnly
{
    public static void main (String [] args)
    {

        for(int i=1; i<=5; i++)
        {
            for(int j=1; j<=10; j++)
            {
                System.out.print((int)Math.round(Math.pow(j, i)) + " ");
            }
            System.out.println();
        }
    }
}

输出为:

  

1 2 3 4 5 6 7 8 9 10

     

1 4 9 16 25 36 49 64 81100

     

1 8 27 64 125 216 343 512 729 1000

     

1 16 81 256 625 1296 2401 4096 6561 10000

     

1 32 243 1024 3125 7776 16807 32768 59049 100000

在这里,我们使用2个循环,外部循环运行5次,因为我们需要将数字1-10提高到1-5的幂。 内部循环运行10次,因为数字是1-10。 我们在内部循环中使用 System.out.print(),因为当所有数字都提高到相同的幂时,我们不希望换行。 当内部循环结束时,我们使用 System.out.println()将所有加起来的数字放在新行中的下一个幂上。

示例-

将1-10提升到幂1,放在第一行。

1-10提升到幂2,放在下一行(即第二行)。 等等...

相关问题