我学习 C 编程有一段时间了,我偶然发现了这个我似乎无法解决的练习:
编写循环嵌套,导致显示以下输出:
0 01 012 0123 01234 012345 01234 0123 012 01 0
到目前为止,我已经成功到达第六排,但我无法完成练习。 这是我为获得此问题的一半解决方案而编写的代码:
#include <stdio.h>
int
main(void)
{
int i, j;
for(i = 1; i <= 6; ++i) {
for(j = 0; j < i; ++j)
printf("%d", j);
printf("\n");
}
return(0);
}
答案经过一些研究,很明确;也许对研究同一主题的人有用,所以它无缘无故地被否决了。
最佳答案
实际上,您可以使用单个嵌套循环来完成此操作:
#include <stdio.h>
int getLength(int i) {
/* Since this is homework, I'll leave this for you to complete. */
if (i < ?) return ?;
else return ?;
}
int main(void) {
for(int i = 0; i < 11; ++i) {
int length = getLength(i);
for(int j = 0; j < length; ++j) {
printf("%d", j);
}
printf("\n");
}
return 0;
}
关于c - 如何解决这个特殊的嵌套 for 循环练习?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10465054/