我想知道这个程序是如何执行的,并且不会抛出任何错误。
void main( )
{
clrscr();
int i ;
for ( i = 1 ; i <= 5 ; printf ( "n%c", 65 ) ) ;
i++ ;
getch();
}
循环将永远打印A。for循环的格式为
for(initialize value; test counter; increment value)
{
do this;
and this;
and this;
}
我的问题是printf("\n%c",65)如何增加值?
for()
之后的尾随;
导致i
在for
内部不递增,从而导致无限循环。
此:
for ( i = 1 ; i <= 5 ; printf ( "n%c", 65 ) ) ;
i++ ;
相当于:
for ( i = 1 ; i <= 5 ; printf ( "n%c", 65 ) ) {} /* Empty loop body. */
i++ ;
从未达到i++
。要更正,请卸下尾部的;
。使用i++
作为for
循环中的迭代表达式会更清楚,而不是printf()
和i
不需要存在于循环体之外:
for (int i = 1; i <= 5; i++)
{
printf ( "n%c", 65 );
}
我的问题是
printf("n %c", 65)
如何增加值?
printf()
返回写入的字符数,因此如果您愿意,可以使用它来增加i
,但有必要更改终止条件以考虑n
字符:
for (int i = 1; i <= 10; i+= printf("n%c", 65));
然而,这一点不如先前的建议明确。
for ( i = 1 ; i <= 5 ; printf ( "n%c", 65 ) ) ;
本身就是一个语句i
在该语句中不递增,因此是无限循环。
这被称为空白循环:它类似于空for循环。
无无限循环
for ( i = 1 ; i <= 5 ; printf ( "n%c", 65 ) ){
i++;
}
只写
void main( )
{
clrscr();
int i ;
for ( i = 1 ; i <= 5 ; printf ( "n%c", 65 ) )
i++ ;
getch();
}
你可以去
因为,如上所述,i++是不可访问的,因为for语句后面的";"等于一个带有空白正文的for。
你可以把这个循环写如下:
for ( i = 1 ; i <= 5 ; printf ( "n%c", 65 ) , i++);
以获得相同的效果并且不写入显式块。
您已自行给定for loop
的格式为
for(initialize value; test counter; increment value)
{
do this;
and this;
and this;
}
但是你用过
for(initialize value; test counter; increment value);
{
do this;
and this;
and this;
}
将;
放在for()
之后将导致执行null语句。这将不允许程序递增i
-导致无限循环。
for(initialize value; condition; increment value/decrement value)
{
do this;
and this;
and this;
}
you can write many initializations, many increments/decrements but we have to write only one condition
即(i=1;i<=5;printf("\n%c",65),i++);这对你有用。