我对这段代码真的很困惑。
我希望它执行以下操作:从“v”值 5 开始,执行其余的函数/计算,将“v”值增加 0.01,执行函数/计算,然后增加“v”再次将值增加 0.01,执行函数...执行此操作 500 次或直到达到“v”值 10.00,以更容易编码的为准。
这是我现在的代码:
//start loop over v
for(iv=5;iv<=500;iv++) {
v=0.01*iv;
//Lots and lots of calculations with v here
}
这是我得到的:我尝试设置 iv<=10 所以它只执行 10 次循环,这样我就可以在整夜打开之前先测试它。它只进行了 6 次循环,从 v=0.05 开始,到 0.1 结束。所以问题是 a) 它没有运行 10 个循环,b) 它不是从 5.00 开始,而是从 0.05 开始。
任何帮助将不胜感激。
编辑:天啊,这么多答案!到目前为止,我已经尝试了两种不同的答案,都有效!我已经盯着这个并更改代码了 3 个小时,不敢相信它如此简单。
I'm really confused on this code.
Here's what I want it to do: Start with a "v" value of 5, carry out the rest of the functions/calculations, increase the "v" value by 0.01, carry out the functions/calculations, then increase the "v" value by 0.01 again, carry out the functions...do this 500 times or until a "v" value of 10.00 is reached, whichever is easier to code.
Here is my code at the moment:
//start loop over v
for(iv=5;iv<=500;iv++) {
v=0.01*iv;
//Lots and lots of calculations with v here
}
Here is what I get: I tried setting iv<=10 so it does 10 loops only just so I could test it first before leaving it on all night. It did only 6 loops, starting at v=0.05 and ending at 0.1. So the problem is that a) it didn't run for 10 loops, b) it didn't start at 5.00, it started at 0.05.
Any help would be appreciated.
EDIT: Holy crap, so many answers! I've tried 2 different answers so far, both work! I've been staring at this and changing code around for 3 hours, can't believe it was so easy.
发布评论
评论(6)
您需要从
iv = 500
开始。如果您想要 10 个循环,并且iv++
是更新,那么您在510
之前停止。原因:
v = 0.01*iv
,因此v = 5
表示iv = 5/0.01 = 500
。至于迭代次数,如果您的 for 循环的形式为for (x = N; x (常量
N
和M
),然后执行max(0, MN)
循环,如果x
在循环中没有改变并且没有奇怪的东西(例如溢出、隐藏的强制转换)负数到无符号数等)发生。编辑
v = iv / 100.0
可能比使用v = 0.01 * iv
更准确。原因:0.01 不能完全用浮点数表示,但 100.0 可以。You need to start at
iv = 500
. and if you want 10 loops, andiv++
is the update, then you stop before510
.Reason:
v = 0.01*iv
, sov = 5
meansiv = 5/0.01 = 500
. As for the number of iterations, if your for loop is of the formfor (x = N; x < M; x++)
(constantN
andM
), thenmax(0, M-N)
loops are executed, ifx
is not changed in the loop and no weird stuff (e.g. overflow, hidden casts of negative numbers to unsigned, etc.) occurs.EDIT
Instead of using
v = 0.01 * iv
,v = iv / 100.0
is probably more accurate. Reason: 0.01 is not exactly representable in floating point, but 100.0 is.更改 SiegeX 的代码,使其使用整数(“更准确”):
Changing SiegeX's code so it uses integers ("more accurate"):
这给了你们两个。这最多会迭代 500 次,但如果 v 值达到(或超过)10.00,则会跳出循环。
如果您只想要其中之一:
10.00 版本:
500 次迭代版本:(
请注意,这不是 C99,它允许在循环中使用更清晰的声明语法)。
This gives you both. This will iterate at most 500 times, but will break out of that loop if the v value reaches (or exceeds) 10.00.
If you wanted only one or the other:
The 10.00 Version:
The 500 iterations version:
(Note that this isn't C99, which allows for a cleaner declaration syntax in the loops).
iv <= 10
不会执行 10 次循环,直到iv
大于 10。iv <= 10
doesn't do it for 10 loops, it does it untiliv
is greater than 10.这应该可以做到
this should do it