C语言 While和for循环没有给出正确的答案



我的代码应该做一个金字塔,但只是给我一条线,为什么?我试过改变for和while循环的条件,没有找到任何解决方案。任何帮助都会很感激!!

#
##
###
####
#####
######
#######
########
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n = get_int("Add the height of the pyramid: ");
int j = 0;
for(int i = 0; i < n ; i++) {
while (j <= i) {
printf("#");
j = j + 1;
}
printf("n");
}

for循环中声明j,以便每次迭代时从0开始。

for(int i = 0; i < n; i++) {
int j = 0;
while (j <= i) {
printf("#");
j = j + 1;
}
printf("n");
}

内部循环也可以重写为for循环。

for(int i = 0; i < n; i++) {
for (int j = i; j >= 0; j--) printf("#");
printf("n");
}

虽然@Unmitigated的答案是正确的,但这将是一个将一些功能分解为函数的好地方。

void print_n_ln(char *str, int n) {
for (; n > 0; n--) {
printf("%s", str);
}
printf("n");
}

:

int main(void) {
int n = get_int("Add the height of the pyramid: ");
for (int i = 1; i <= n; i++) 
print_n_ln("#", i);
return 0;
}

虽然迭代解决方案(嵌套的for()循环)是最简单的,但这可能是发现递归的好时机。只要金字塔没有高到可能导致堆栈溢出的程度,下面的代码就可以工作(将收集/验证用户输入作为练习)

#include <stdio.h>
#include <cs50.h>
void print( int n ) {
if( n > 1 )
print( n - 1 );
while( n-- )
putchar( '#' );
putchar( 'n' );
}
int main() {
print( 7 );
return 0;
}

putchar()是一个比printf()简单得多的函数,应该在输出一个简单的单个字符时使用(为了速度和效率)

如果你仔细思考所呈现的操作,你就会理解递归,以及它有时是如何被用来解决问题的。

另一个(尽管"有限")解决方案如下:

int main() {
char wrk[] = "################";
int i = sizeof wrk - 1; // 'i' starts as the 'length' of the string
int want = 7;
while( want-- )
puts( wrk + --i ); // adding decreasing values of 'i' prints longer strings
return 0;
}

puts()将输出一个字符串到stdout,同时附加一个'换行符'。
注意:它的更一般的兄弟函数(fputs())以类似的方式工作,但不会为您附加LF。

做事情通常有很多种方法。

编辑:
这是另一个使用指针的极简解决方案。这个使用了"编译时间"。字符串,因此不容易受到用户的影响(但如果你聪明的话,可以这样做。)

#include <stdio.h>
#include <string.h>
int main() {
char want[] = "#######";
char *p = want + strlen( want );
while( --p >= want) puts( p );
return 0;
}

相关内容

最新更新