[英]printing numbers flipped in pyramid style
I am trying to print something like this using for loops: 我试图使用for循环打印这样的东西:
1
121
12321
1234321
123454321
int mid = 1;
System.out.println(" " + mid + " ");
mid++;
for(int i = 1; i <=4; i++){
//left spaces
for(int x = 4; x > i; x--){
System.out.print(" ");
}
//left diguts
for(int z = 1; z <= i; z++){
System.out.print(z);
}
//middle digit
System.out.print(mid);
mid++;
//right diguts
for(int b = 1; b <= i; b++){
System.out.print(b);
}
//right spaces
for(int y = 4; y > i; y--){
System.out.print(" ");
}
System.out.println();
}
But i kept on getting: 但我继续得到:
1
121
12312
1234123
123451234
For the right digits you will have to print the digits in reverse order so make the change as below: 对于正确的数字,您必须以相反的顺序打印数字,以便进行如下更改:
//right diguts
for(int b = 1; b <= i; b++){
System.out.print(b);
}
change this to 将此更改为
//right diguts
for(int b = i; b > 0; b--){
System.out.print(b);
}
Actually there is no need to separate 1 out. 实际上没有必要将1分开。 You can include it in common logic:
您可以将其包含在通用逻辑中:
public class Pyramid {
public static void main(String[] args) {
int mid = 1;
for (int i = 0; i <= 4; i++) {
// left spaces
for (int x = 4; x > i; x--) {
System.out.print(" ");
}
// left digits
for (int z = 1; z <= i; z++) {
System.out.print(z);
}
// middle digit
System.out.print(mid);
mid++;
// right digits
for(int b = i; b > 0; b--){
System.out.print(b);
}
// right spaces
for (int y = 4; y > i; y--) {
System.out.print(" ");
}
System.out.println();
}
}
}
This is actually nice golf puzzle! 这实际上是很棒的高尔夫拼图! I did this only using two loops!
我只使用两个循环做到了这一点! :)
:)
int n = 5;
for(int i=0; i < n; i++){
for(int j=0; j < 2*n; j++){
int abs = Math.abs(n-j);
System.out.print(abs>i ? " " : i-abs+1);
}
System.out.println();
}
Output: 输出:
1
121
12321
1234321
123454321
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.