gpt4 book ai didi

c - C中的for循环格式

转载 作者:太空狗 更新时间:2023-10-29 15:45:56 25 4
gpt4 key购买 nike

我想知道这个程序是如何执行的并且没有抛出任何错误。

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++。要更正,请删除结尾的 ;。在 for 循环中使用 i++ 作为迭代表达式会更清楚,而不是 printf()i 不需要存在于循环体之外:

for (int i = 1; i <= 5; i++)
{
printf ( "\n%c", 65 );
}

My question is how can printf("\n %c", 65) increment the value?

printf()返回写入的字符数,因此如果您愿意,可以使用它来递增 i 但有必要更改终止条件以说明 \n 字符:

for (int i = 1; i <= 10; i+= printf("\n%c", 65));

但是,这不如之前的建议清楚。

关于c - C中的for循环格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17925158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com