我是个C和编程新手。我想创建一个我在类测试中看到的数字金字塔。我设法做到了,但问题是,当数字超过9时,金字塔就变得很棒。this is what I wanted to achieve without writing a lot of IFs
我的代码:
#include <stdio.h>
int strlen(char *str);
int main(int argc, char **args){
char spaces[] = {"| "};
int i = 1, line = 1; //line number of numbers per line
while(spaces[strlen(spaces)-1] != '|'){
printf("%s", spaces);
for(int k = 0; k < line; k++){
printf("%d", i);
i++;
}
printf("\n");
spaces[strlen(spaces)-1] = '\0';
line += 2;
}
}
int strlen(char *str){
int i = 0;
while(*(str + i))
i++;
return i;
}
发布于 2021-11-18 01:01:15
您展示了您希望在不编写大量IFs的情况下实现的功能:打印字段宽度为6的数字金字塔。您的主要方法是正确的:在每行中,首先打印前导空格,然后打印数字。缺少的是说明前导空格的字段宽度以及数字本身。例如,可以通过将while
循环更改为
int lines = 16; // how many lines you want
while (lines--)
{
// in this line, we need leading spaces for `lines` numbers
printf("%*s", lines*6, ""); // you chose 6 spaces per number
// print each number with the chosen width
for (int k = 0; k < line; k++) printf("%-6d", i++);
puts("");
line += 2;
}
https://stackoverflow.com/questions/69993174
复制相似问题