[英]Interesting increment operator in C (in a while loop)
I want to implement the factorial algorithm, and the following code gives me wrong result for factorial(5) 我想实现阶乘算法,下面的代码给我阶乘(5)的错误结果
int factorial(int n)
{
int i = 1, ret = 1;
while(i++<=n)
ret *= i;
return ret;
}
Looks like the code will continue to run even when i = 6, I don't understand why the while loop didn't stop. 看起来即使i = 6时代码也将继续运行,我不明白为什么while循环没有停止。
You are using a post-increment operator which means the final check for i <= n
happens before i
is incremented for the final time. 您使用的递增运算符,这意味着最后的检查为
i <= n
之前发生i
被递增为最后的时间。 In other words, when i
is 5 your code: 换句话说,当
i
5岁时,您的代码:
check if i <= 5 -> true
increment i -> i is now 6
execute loop -> executes for i = 6
check if i <= 5 -> false (i is now 6)
You should change to: 您应该更改为:
while(++i <= n)
Try to do one thing per statement. 尝试为每个语句做一件事。
int factorial(int n)
{
int i = 1, ret = 1;
while(i<=n)
{
i++;
ret *= i;
}
return ret;
}
Check the differences between the versions above and below this text. 检查此文本上方和下方的版本之间的差异。
int factorial(int n)
{
int i = 1, ret = 1;
while(i<=n)
{
ret *= i;
i++;
}
return ret;
}
i++
returns the value of i
and only then increments i
. i++
返回的值i
然后才递增i
。 (As opposed to ++i
which first incerements i
and returns incremented value) (与
++i
相反,它首先对i
递增,然后返回递增的值)
That's how i++
works. 这就是
i++
工作方式。 you need ++i
你需要
++i
You are doing one extra iteration of the loop. 您正在执行循环的额外迭代。
Instead of (i++<=n)
, what you really want is making it (i<=n)
and then add the i++;
而不是
(i++<=n)
,您真正想要的是制作它(i<=n)
然后添加i++;
after the ret*=1
. ret*=1
。
This is actually much more cleanly done using a for-loop IMHO. 实际上,使用for循环恕我直言可以更干净地完成此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.