我开始学习c++,我得到了这个简单的程序: (我提前为我的英语道歉)
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<double> time_vector(int interval[], float increment)
{
vector<double> time;
for (double i=interval[0]; i<=interval[1]; i=i+increment)
time.push_back(i);
return time;
}
int main(int argc, char** argv) {
int interval[] = {0,3};
float increment = 0.1;
vector<double> time = time_vector(interval, increment);
for (vector<double>::iterator it=time.begin(); it!=time.end(); ++it)
cout << *it << " ";
return 0;
}
time_vector 函数的想法是创建一个范围为 [a,b] 的 vector ,并按增量值自增。这将模仿来自 matlab 的命令
a:increment:b
但是当我运行它时,我得到了这个:
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 0
如您所见,最后一个元素不是 3.0,它应该是。我做的对吗?
最佳答案
很可能是浮点精度问题。参见 floating point guide (每个程序员都应该了解的浮点运算知识)
因此 0.1
在 IEEE754 中不能完全表示.
附言。这本身不是 C++ 问题。您会在 C、Ada 或 Fortran 中遇到同样的问题。
关于c++ - for 循环的问题(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24912940/