我试图生成以数字一 (1) 开头的金字塔,每行中的第一个数字决定行数。此外,该行中的第一个数字还决定了该顺序中的数字数量(根据模块 10)。根据模块 10,我们通过将左侧的数字与其上方的数字相加来计算一行中的所有其他数字。
int n = 12;
int i, j;
for (i = 1; i <= n; i++) {
for (j = 0; j <= i; j++) {
int module = i % 10;
System.out.print(module + " ");
}
System.out.println();
}
}
通过我的实现,我得到了
1 1
2 2 2
3 3 3 3
4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6 6 6
7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9
0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2
实际结果应该是
1
2 3
3 5 8
4 7 2 0
5 9 6 8 8
6 1 0 6 4 2
7 3 4 4 0 4 6
8 5 8 2 6 6 0 6
9 7 2 0 2 8 4 4 0
0 9 6 8 8 0 8 2 6 6
1 1 0 6 4 2 2 0 2 8 4
2 3 4 4 0 4 6 8 8 0 8 2
我错过了什么?
最佳答案
首先编写一个辅助方法来计算要显示的数字。此方法将行索引和列索引或行号和列号作为参数,无论您更喜欢什么。假设我们对行和列使用基于 0 的索引,我们可以为该方法定义以下值:
- 当列索引为 0 时(即我们位于第一列),返回值为行索引 + 1 模 10。
- 当行索引为 0(因此我们位于顶部)时,返回值为 1。
- 对于所有其他位置,我们使用辅助方法的递归调用将“左边的数字”与“上面的数字”相加。
辅助方法将如下所示:
/**
* Calculate the digits. The arguments are 0 based.
*
* @param row The row index
* @param column The column index
* @return The digit to display
*/
public static int calculateDigit(int row, int column) {
if (row < 0) {
throw new IllegalArgumentException("The row index must not be negative");
}
if (column < 0) {
throw new IllegalArgumentException("The column index must not be negative");
}
if (column == 0) {
return (row+1) % 10; // simply return the row number
}
if (row == 0) {
return 1; // in the first row, so it is the "1"
}
// calculate the new number based on the expression
// "adding the number from the left and the number above it"
int left = calculateDigit(row, column-1);
int above = calculateDigit(row-1, column-1);
int sum = left + above;
int modulo = sum % 10;
return modulo;
}
您可以在已有的两个简单 for
循环中使用此辅助方法。
for (int r=0; r<10; r++) {
for (int c=0; c<=r; c++) {
int value = calculateDigit(r, c);
System.out.print(value+" ");
}
System.out.println();
}
这将为您带来预期的输出:
1
2 3
3 5 8
4 7 2 0
5 9 6 8 8
6 1 0 6 4 2
7 3 4 4 0 4 6
8 5 8 2 6 6 0 6
9 7 2 0 2 8 4 4 0
0 9 6 8 8 0 8 2 6 6
关于java - 生成金字塔以显示模块 10 中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56410653/