简体   繁体   English

为什么我的for循环永远不会结束?

[英]Why does my for loop never end?

So, I have this code that is supposed to add each range that is going to be tested to the 'freqDistRanges' vector. 因此,我有这段代码应该将要测试的每个范围添加到“ freqDistRanges”向量中。 'values' is a vector of type double that holds the user input. “值”是double类型的向量,用于保存用户输入。 My problem is that if I input less than ten values into the 'values' array the for loop never ends. 我的问题是,如果我在“值”数组中输入少于十个值,则for循环永远不会结束。 I don't see why this would be, for example if there was only one value entered freqDistRange would equal 0.1. 我不知道为什么会这样,例如,如果仅输入一个值,freqDistRange将等于0.1。 The for loop would stop when i > 0.1 and i would equal 0.1 on the second iteration and would be 0.2 on the second, which should end the for loop. 当i> 0.1时,for循环将停止,并且在第二次迭代中i等于0.1,在第二次迭代时i将等于0.2,这将结束for循环。 What am I missing here, I feel like it is something simple that I overlooked. 我在这里想念的是什么,我觉得这很简单,我忽略了。 Thanks for any help. 谢谢你的帮助。

double freqDistRange = ((double)values.size() / 10); // there will be ten ranges

// add each range to the 'ranges' vector
for (auto i = 0; i <= ((double)values.size() * freqDistRange); i +=     freqDistRange)
        freqDistRanges.push_back(i);

i is an int , here, and can only hold integral values. i在这里是一个int ,并且只能保存整数值。 If i is 0 , and you add 0.1 to it, it'll still be 0 . 如果i0 ,并加上0.1 ,则它仍为0 If you add 0.1 to it a million times, it'll still be 0 . 如果将0.1加一百万次,它仍然0

You should change: 您应该更改:

auto i = 0;

to either: 可以:

double i = 0;

or: 要么:

auto i = 0.0;

There are no benefits to using auto in this particular case if you have to make sure to choose an initial value of the type you need. 如果必须确保选择所需类型的初始值,则在这种特殊情况下使用auto没有任何好处。 If you know you need type double , you may as well explicitly declare it as a double . 如果知道需要double类型,则最好将其声明为double

The problem is that you intended a double as a loop counter, however auto i = 0; 问题是您打算将double用作循环计数器,但是auto i = 0; deduces type based on 0 which is an int . 推导基于0类型,它是一个int This is a pitfall to be aware of when using auto in a for loop. for循环中使用auto时要意识到这是一个陷阱。 See here for another SO question on the topic. 有关此主题的另一个SO问题, 请参见此处

However, if you want to have exactly 11 steps then using double as the variable type is not a good idea. 但是,如果你想有确切的11级然后使用double作为变量的类型是不是一个好主意。 This is because floating-point arithmetic is inherently not perfectly precise, so due to rounding errors you could get either 10 or 12 steps instead. 这是因为浮点运算本质上不是很精确,因此,由于舍入误差,您可能会得到10或12步。

To get precise behaviour use an integral type as the loop counter. 要获得精确的行为,请使用整数类型作为循环计数器。 Here: 这里:

double freqDistRange = values.size() / 10.0;

for (int i = 0; i <= 10; ++i)
{
    freqDistRanges.push_back( i * freqDistRange );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM