Reputation: 45
So, I have this code that is supposed to add each range that is going to be tested to the 'freqDistRanges' vector. 'values' is a vector of type double that holds the user input. My problem is that if I input less than ten values into the 'values' array the for loop never ends. I don't see why this would be, for example if there was only one value entered freqDistRange would equal 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. 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);
Upvotes: 0
Views: 861
Reputation: 141544
The problem is that you intended a double
as a loop counter, however auto i = 0;
deduces type based on 0
which is an int
. This is a pitfall to be aware of when using auto
in a for
loop. See here for another SO question on the topic.
However, if you want to have exactly 11 steps then using double
as the variable type is not a good idea. 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.
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 );
}
Upvotes: 1
Reputation: 25908
i
is an int
, here, and can only hold integral values. If i
is 0
, and you add 0.1
to it, it'll still be 0
. If you add 0.1
to it a million times, it'll still be 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. If you know you need type double
, you may as well explicitly declare it as a double
.
Upvotes: 4