从一开始重复循环,直到新的数字中断,然后在c中再次循环



所以我对如何在C中解决这个问题感到困惑。如果我能理解逻辑,这个问题的答案更有可能解决。但我似乎听不懂。如果题目与问题的解释不符,我很抱歉。因此:

在C中,循环使用类似的for,for(x=0;x<10;x++),这将导致同时循环而不中断。例如:

for(x=0;x<10;x++)
printf("this is x = %d",x);

结果示例:

this is x = 0
this is x = 1
.
.
this is x = 10

因此,如何循环,但会插入每个新数字并重新开始,然后中断/暂停直到新数字,以此类推。例如:

for(x=0;x<//variables;x++)
printf("this is x = %d",x);

结果:

(start)
this is x = 0
this is x = 1
(over/break)
(start)
this is x = 0
this is x = 1
this is x = 2
(over/break)
(start)
this is x = 0
this is x = 1
this is x = 2
this is x = 3
(over/break)
.
.
.
(start)
this is x = 0
this is x = 1
this is x = 2
this is x = 3
.
.
.
this is x = 10
(over/break)

那么如何做到这一点呢?这可能看起来很简单,但我找不到解决方案。我希望这个解释能把问题弄清楚。非常感谢。

只需使用嵌套for循环,例如

for ( int i = 0; i < 10; ++i )
{
for ( int x = 0; x  <= i + 1; ++x )
{
printf( "this is x = %dn", x );
}
}

这是一个演示程序

#include <stdio.h>
int main( void ) 
{
for ( int i = 0; i < 10; ++i )
{
for ( int x = 0; x  <= i + 1; ++x )
{
printf( "this is x = %dn", x );
}
}    
}

其输出为

this is x = 0
this is x = 1
this is x = 0
this is x = 1
this is x = 2
this is x = 0
this is x = 1
this is x = 2
this is x = 3
this is x = 0
this is x = 1
this is x = 2
this is x = 3
this is x = 4

等等

如果你想用像这样的空行来分隔输出

this is x = 0
this is x = 1
this is x = 0
this is x = 1
this is x = 2
this is x = 0
this is x = 1
this is x = 2
this is x = 3
this is x = 0
this is x = 1
this is x = 2
this is x = 3
this is x = 4
...

然后像一样写循环

for ( int i = 0; i < 10; ++i )
{
for ( int x = 0; x  <= i + 1; ++x )
{
printf( "this is x = %dn", x );
}
putchar( 'n' );
}    

如果你只想使用一个for循环,那么程序可以按照以下方式查找

#include <stdio.h>
int main( void ) 
{
for ( int x = 0, i = x + 1;  i <= 10;  )
{
printf( "this is x = %dn", x );
if ( x == i )
{
putchar( 'n' );
++i;
x = 0;
}
else
{
++x;
}
}    
}

只有我们2用于循环而不是1:

for (y = 0; y < 10; y++)
for (x = 0; x < y; x++)
printf("this is x = %d",x);

如果不想更改最大值,只需更改第一个循环(y < 10(条件下的值即可。

两个循环,外部循环递增内部循环的最大计数。

最新更新