我需要用这样的“循环”来显示10个数字:
1
2 3
4 5 6
7 8 9 10
我用下面的代码成功地做到了。但我觉得一定有更简单的方法来做这件事。如果我需要做同样的模式,但有1000个数字呢?那会有很多代码。
#include <stdio.h>
int main(){
int x;
x=1;
do {
printf("%i \n", x);
x++;
} while (x<=1);
do {
printf("%i ", x);
x++;
} while (x<=3); {
printf("\n");
}
do {
printf("%i ", x);
x++;
} while (x<=6); {
printf("\n");
}
do {
printf("%i ", x);
x++;
} while (x<=10); {
printf("\n");
}
return 0;
}
最佳答案
#include <stdio.h>
void main() {
int row = 1;
int column = 1;
for (int i = 1; i <= 10; i++) {
printf("%d", i);
if (column == row) {
printf("\n");
row++;
column = 1;
}
else {
printf(" ");
column++;
}
}
}
关于c - 如何在[C]中编写适当的循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39670157/