c++ - for 循环的问题(初学者)

标签 c++ vector

我开始学习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.1IEEE754 中不能完全表示.

附言。这本身不是 C++ 问题。您会在 C、Ada 或 Fortran 中遇到同样的问题。

关于c++ - for 循环的问题(初学者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24912940/

相关文章:

c++ - std::cin 如何同时返回 bool 和自身?

c++ - 无需任何库函数即可将 float 转换为字符串的高效方法

c++ - 从函数发回 vector

c++帮助将 vector 索引传递给函数

c++ - 如何使用 C++11 可变参数模板来定义由 vector 元组支持的元组 vector ?

c++ - 从 vector 和 QVBoxLayout 中删除

C++ 将八个 boolean 值压缩为一个字符

c++ - 段错误,没有核心转储

c++ - 如何理解 pthread_cancel 原因 "terminate called without an active exception"?

java - Mahout 中 RandomAccessSparseVectors 的余弦距离