gpt4 book ai didi

c - c 中的重复语句

转载 作者:行者123 更新时间:2023-11-30 15:07:48 25 4
gpt4 key购买 nike

当执行for语句时,计数器变量的值必须加1,因为我使用了预自增运算符。

#include <stdio.h>
int main (void)
{
unsigned int counter ;
for ( counter = 1; counter <= 10; ++counter /*here is problem*/) {
printf( "%u\n", counter );
}
}

问题-

When the program is executed, the value of counter variable initially is 1 instead of 2.

最佳答案

for循环中

for(first statement; second statement; third statement){//...}; 

第三条语句通常用于更新,在每次迭代结束时执行,因此您的变量counter将为1在第一次迭代期间,并在第一次迭代结束时变为 2

<小时/>

如果您想让 counter 变量在迭代开始时递增,请尝试在 for 循环的第二个语句中使用它 ++counter :

for ( counter = 1; ++counter <= 10;)

原因:

因为,for 循环是一个预测试循环,并且条件通常是在每次迭代开始时检查第二条语句。因此,现在您的计数器在每次迭代开始时都会递增

关于c - c 中的重复语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37933508/

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