首页 > 解决方案 > 给定N个数字显示M*M格式

问题描述

我们在第一行给出一个数字 (n) 程序输出:接下来的行包含空格分隔的整数,描述第一种排列。

n=m^2
例如:9

Output:1  2  3
       4  5  6
       7  8  9

例如:16

输出:
作为一个

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n;
        int m;
        System.out.println("Enter number of team");
        n = scanner.nextInt();

        m = (int) Math.sqrt(n);

        int[][] array = new int[m][m];


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

    }

}

购买我的程序输出

条目:3

输出:

123

123

123

标签: javaalgorithm

解决方案


你还没有问任何问题,但我认为你的程序给出了错误的答案(实际上是这样),你不知道为什么。例如:对于 n=16,它会打印:

1234
1234
1234
1234

以下代码片段负责:

array[i][j]=j+1;
System.out.print(array[i][j]);

首先,您不打印空格,因此不会分隔数字。其次,您必须使用另一个公式:(i*m+j+1因为数字取决于两者ij)。此外,保留数组没有意义,但这不是错误。

建议修正:

System.out.print(m*i+j+1 + " ");

推荐阅读