c++ - 静态转换如何在 C++ 中保持数字的精度?

标签 c++ c++11

在很长一段时间没有编程之后,我正在为下个月的作业而忙于 C++。我了解到变量可以溢出:具体来说,float 类型的变量不会像 double 类型那样保存那么多的小数。但是,我尝试了这段代码:

#include <iostream>
#include <iomanip> 


int main()
{
    using namespace std;

    cout << setprecision(20);

    double t(0.1);
    float g(0.1);
    cout << t << endl;
    cout << g << endl;
    static_cast<float>(t);
    cout << t << endl;


}

而且,令我惊讶的是,第一个和最后一个(double t 和 float t)的精度相同,而 float g 的精度更低。这对我来说似乎有点违反直觉,static_cast 如何保持数字的精度?

非常感谢。

最佳答案

那是因为你没有为任何东西分配 static_casted 值:

#include <iostream>
#include <iomanip>

int main() {
    using namespace std;

    cout << setprecision(20);

    double t(0.1);
    float g(0.1);
    cout << t << endl;
    cout << g << endl;
    g = static_cast<float>(t); // There was no assignment in your code
    cout << g << endl;
}

现在输出:

0.10000000000000000555
0.10000000149011611938
0.10000000149011611938

关于c++ - 静态转换如何在 C++ 中保持数字的精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38044785/

相关文章:

c++ - 在运行时加载 opengl/directx API 函数

c++ - std::auto_ptr 到 std::unique_ptr

C++ 段错误有时但

c++ - 在派生类中重载运算符

c++ - 使用 Boost::Asio 发送 TCP SYN 数据包

c++ - QString 和 stdstring 组合在 std::stringstream 中不起作用 - 编译错误

c++ - Cython VS C++ 性能比较?

c++ - 自动类型推导并将 lambda 传递给 std::function 参数

c++ - 如何从一个函数锁定 shared_mutex 并从另一个函数解锁它?

c++ - 分离复制/move 赋值运算符