绘制数字菱形 [英] Drawing numeric diamond
本文介绍了绘制数字菱形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要绘制一个数字菱形,例如高度为 9
:
I need to draw a numeric diamond, for example with a height of 9
:
1
222
33333
4444444
555555555
4444444
33333
222
1
我编写了代码,并设法获得了相同的钻石,但带有星星.我想要这些数字.我怎样才能做到这一点?到目前为止,这是我所做的:
I wrote the code and I managed to get the same diamond, but with stars. I want it with these numbers. How can I do that? Here is what I have done so far:
for (int i = 1; i < 10; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("a");
System.out.print("\n");
}
for (int i = 7; i > 0; i -= 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("b");
System.out.print("\n");
}
推荐答案
关于您的代码:
-
System.out.print("\ n");
应该替换为System.out.println()
. - 您应该使用动态高度,而不要硬编码9.
- 它会打印正确的图案,只是打印出的图案是错误的:您应该打印循环的索引,然后打印循环代码,而不是打印
"a"
和"b"
看看你能从那里得到什么.这是@ Tsung-Ting Kuo解决方案.
System.out.print("\n");
should be replaced bySystem.out.println()
.- You should a dynamic height instead of hard-coding 9.
- It prints the correct pattern, only what is printed is wrong: instead of printing
"a"
and"b"
, you should print the index of the loop and see what you can get from there. This is @Tsung-Ting Kuo solution.
在我看来,您可以用更少的循环和更容易理解的方式来做到这一点.考虑以下算法:
You can do it with fewer loops and a more understandable in my view. Consider the following algorithm:
- 对于模式的每一行(因此该行从0变为
height
) - 对于模式的每一列(因此该列从0变为
height
) - 在图表的右上角,左上角,右下角或左下角时,我们需要打印一个空格.
- 左上:这是当列小于
height/2-row-1
时 - 左下:这是当列小于
row-height/2
时- 将这两个表达式组合为一个表达式,这是当列小于
height/2-min
时,其中min = Math.min(row + 1,height-row)
.
- For each row of the pattern (so the row goes from 0 to
height
excluded) - For each column of the pattern (so the column goes from 0 to
height
excluded) - We need to print a space when we are in the upper-right, upper-left, lower-right or lower-left of the diagram.
- Upper-left: This is when the column is less than
height/2-row-1
- Lower-left: This is when the column is less than
row-height/2
- Factoring these two expressions in a single one, this is when the column is less than
height/2 - min
wheremin = Math.min(row+1, height-row)
.
- 将这两个表达式组合为一个表达式,这是当列大于
height/2 + min
时,其中min = Math.min(row + 1,height-row)
.
变成代码:
public static void main(String[] args) { int height = 9; for (int row = 0; row < height; row++) { for (int column = 0; column < height; column++) { int min = Math.min(row+1, height-row); if (column <= height / 2 - min || column >= height / 2 + min) { System.out.print(" "); } else { System.out.print(min); } } System.out.println(); } }
示例输出:
1 222 33333 4444444 555555555 4444444 33333 222 1
这篇关于绘制数字菱形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Factoring these two expressions in a single one, this is when the column is less than
- Upper-left: This is when the column is less than
- 将这两个表达式组合为一个表达式,这是当列小于
- 左上:这是当列小于
查看全文