我如何格式化这个嵌套的 for 循环金字塔,使其看起来像我需要的那样?
How do I format this nested for loop pyramid to look like how I need it to?
我正在练习嵌套 for 循环练习,想制作一个打印如下内容的程序:
How many rows do you want?: 4
0
000
00000
0000000
到目前为止,这是我的程序:
#include <stdio.h>
int main(void) {
int x;
printf("How many rows do you want in the pyramid? (newlines included): ");
scanf("%d", &x);
for (int i = 1; i <= x; i++) {
printf("\t");
for (int j = 1; j <= i; j++) {
if (i % 2 == 0) {
break;
}
printf("0");
}
printf("\n");
}
return 0;
}
我的代码像我希望的那样工作,但它输出的金字塔是这样的:
How many rows do you want in the pyramid? (newlines included): 6
0
000
00000
如何将其格式化为真正的金字塔而不是像现在这样的直角三角形?我也知道还有其他方法可以做到这一点,但我试图在这个练习中发挥我的创造力。
您不需要跳过行来打印奇数个零。使用 2*i+1
.
2*i
永远是偶数,所以 2*i+1
永远是奇数。
现在您只需要在打印零之前添加 space。为此,您使用另一个循环,当 i
变大时,它打印更少的 spaces。您可以使用条件 x-i
.
#include <stdio.h>
int main(void)
{
int x;
printf("How many rows do you want in the pyramid? (newlines included):\n");
scanf("%d", &x);
for (int i = 0; i < x; i++) {
for (int j = 1; j < x-i; j++) {
printf(" ");
}
for (int j = 0; j < 2*i+1; j++) {
printf("0");
}
printf("\n");
}
return 0;
}
我正在练习嵌套 for 循环练习,想制作一个打印如下内容的程序:
How many rows do you want?: 4
0
000
00000
0000000
到目前为止,这是我的程序:
#include <stdio.h>
int main(void) {
int x;
printf("How many rows do you want in the pyramid? (newlines included): ");
scanf("%d", &x);
for (int i = 1; i <= x; i++) {
printf("\t");
for (int j = 1; j <= i; j++) {
if (i % 2 == 0) {
break;
}
printf("0");
}
printf("\n");
}
return 0;
}
我的代码像我希望的那样工作,但它输出的金字塔是这样的:
How many rows do you want in the pyramid? (newlines included): 6
0
000
00000
如何将其格式化为真正的金字塔而不是像现在这样的直角三角形?我也知道还有其他方法可以做到这一点,但我试图在这个练习中发挥我的创造力。
您不需要跳过行来打印奇数个零。使用 2*i+1
.
2*i
永远是偶数,所以 2*i+1
永远是奇数。
现在您只需要在打印零之前添加 space。为此,您使用另一个循环,当 i
变大时,它打印更少的 spaces。您可以使用条件 x-i
.
#include <stdio.h>
int main(void)
{
int x;
printf("How many rows do you want in the pyramid? (newlines included):\n");
scanf("%d", &x);
for (int i = 0; i < x; i++) {
for (int j = 1; j < x-i; j++) {
printf(" ");
}
for (int j = 0; j < 2*i+1; j++) {
printf("0");
}
printf("\n");
}
return 0;
}