我正在解决 CS50 的一个问题,其中我必须根据用户输入的高度创建一个由 #
组成的金字塔。这是我到目前为止所拥有的,但是对于 8 的高度,它只迭代一次。对于 7 的高度,我得到大约四行,只是一堆 #
。
//Create GetPosInt() function
int GetPosInt(void) {
int n = GetInt();
while (n <= 0) {
printf("That won't work...\nRetry: ");
n = GetInt();
}
return n;
}
int main(void) {
printf("How high should Mario's pyramid be?\nHeight: ");
int h = GetPosInt();
while (h > 23) {
printf("Try something smaller!\nHeight: ");
h = GetPosInt();
}
char str[] = "##";
char strad[] = "#";
int l = h + 1;
for (int i = 0; i < h; i++) {
printf("%*s\n", l, str);
strcat(str, strad);
return 0;
}
}
这是我第一次尝试使用 string.h 库。
请仅提供有关修复我的代码的提示 - 我确信还有其他方法,但如果可以通过这种方式,我想在类里面保留它!
最佳答案
您的 str
数组/C 字符串没有空间连接 2 个字符以上的其他字符。
作为一个小小的改变,你可以做:
char str[128] = "";
strcat(str, "##");
关于c - C "for"循环出现问题 - 不会迭代过去的第一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37212821/