打印 ASCII 金字塔

Printing ASCII Pyramid

我正在尝试打印以下 ASCII 金字塔。

A B C D E F G F E D C B A
A B C D E F   F E D C B A 
A B C D E       E D C B A 
A B C D           D C B A 
A B C               C B A 
A B                   B A 
A                       A 

但我得到以下输出:

A B C D E F G       F E D C B A
A B C D E F     F E D C B A 
A B C D E         E D C B A 
A B C D             D C B A 
A B C                 C B A 
A B                     B A 
A                         A

第一行乱七八糟。谁能帮我得到想要的输出?

代码如下:

#include <stdio.h>;
#include <stdlib.h>;

void main() {
  unsigned long int x, y, z;
  printf("\nTHIS PROGRAM PRINTS ASCII PYRAMID \n");
  char c;
  y = 71;
  z = 12;
  for (int i = 0; i < 7; i++) {

    for (int j = 65; j <= y; ++j) {
      printf("%c ", j); /*prints left side of the string */
    }

    for (int k = 0; k < 2 * i; ++k) {

      printf("  "); /*prints spaces between the strings */
    }
    for (int l = y; l > 64; l--) {
      if (l == 71) {
        for (int p = 70; p > 64; p--)
          printf("%c ", i);
      } else
        printf("%c ", l); /* prints right part of the string */
    };
    y = y - 1;
    printf("\n");
  }
}

我在你的代码中发现了两个主要问题。

首先,您要在左右字符之间打印一对额外的 2 个空格。

其次,

for (int p = 70; p > 64; p--)
  printf("%c ", i);

部分正在发出垃圾(控制字符)和多余的空格。

这个程序(还有一些小的修正)似乎运行良好。

/* remove extra semicolons */
#include <stdio.h>
#include <stdlib.h>

/* use standard return type */
int main() {
  unsigned long int x, y, z;
  printf("\nTHIS PROGRAM PRINTS ASCII PYRAMID \n");
  char c;
  y = 71;
  z = 12;
  for (int i = 0; i < 7; i++) {

    for (int j = 65; j <= y; ++j) {
      printf("%c ", j); /*prints left side of the string */
    }

    /* reduce number or pairs of spaces to print */
    for (int k = 0; k < 2 * i - 1; ++k) {

      printf("  "); /*prints spaces between the strings */
    }
    for (int l = y; l > 64; l--) {
      /* remove extra printing */
      if (l != 71)
        printf("%c ", l); /* prints right part of the string */
    };
    y = y - 1;
    printf("\n");
  }
}