我是 C 编程的新手,在编程练习中遇到了一些困难,我相信这对于任何了解 C 的人来说都很简单,不幸的是你必须遵守练习的规则。
这是练习:
Have a program request the user to enter an uppercase letter. Use nested loops to produce a pyramid pattern like this:
A ABA ABCBA ABCDCBA ABCDEDCBA
The pattern should extend to the character entered. For example, the preceding pattern would result from an input value of E. Hint: Use an outer loop to handle the rows. Use three inner loops in a row, one to handle the spaces, one for printing letters in ascending order, and one for printing letters in descending order.
所以我走到这一步:
#include <stdio.h>
int main(void) {
int rows;
int spaces;
char asc;
char desc;
char input;
printf("Please enter an uppercase letter: ");
scanf("%c", &input);
for (rows = 'A'; rows <= input; rows++) {
for (spaces = input; spaces > rows; spaces--) {
printf(" ");
}
for (asc = 'A'; asc <= rows; asc++) {
printf("%c", asc);
}
for (desc = asc - 2; desc >= rows; desc--) {
printf("%c", desc);
}
printf("\n");
}
return 0;
}
最佳答案
你非常接近:
for (desc = asc - 2; desc >= 'A'; desc--) {
请注意,在第二个内循环之后,asc
为rows + 1
。然后将 desc
初始化为 rows - 1
。您应该能够明白为什么 >= rows
是错误的,并且不会导致迭代。
正确的条件是 >= 'A'
。
关于c - 帮助进行简单的 C 编程练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4310939/