java - 给定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
解决方案
你还没有问任何问题,但我认为你的程序给出了错误的答案(实际上是这样),你不知道为什么。例如:对于 n=16,它会打印:
1234
1234
1234
1234
以下代码片段负责:
array[i][j]=j+1;
System.out.print(array[i][j]);
首先,您不打印空格,因此不会分隔数字。其次,您必须使用另一个公式:(i*m+j+1
因为数字取决于两者i
和j
)。此外,保留数组没有意义,但这不是错误。
建议修正:
System.out.print(m*i+j+1 + " ");
推荐阅读
- javascript - 如何重现 Google 的浮动/固定实时比分?
- java - Ignite Compute:客户端不在时是否可以继续执行作业?(以崩溃为例)
- javascript - 如何将自定义指令属性传递给 Angular 1.5 中的自定义指令子元素?
- google-chrome - 如何使网站可通过 chrome 搜索?
- python - Nginx/Apache2 WebSocket 连接失败:WebSocket 握手期间出错:意外响应代码:404
- mysql - 如何从 node.js 中的单个语句编写多个 SQL 查询?
- javascript - 这里地图:检查多边形是否包含点?
- sql - SQL - 按日期标记最近的条目
- excel - 使用 VBA 的多重过滤条件
- sql - 使用 CASE 作为 dblink 的一部分来获取数据