【问题标题】:How does a static cast conserve a number's precision in C++?静态转换如何在 C++ 中保持数字的精度?
【发布时间】:2016-06-27 01:32:57
【问题描述】:

在很长一段时间没有编程之后,我正在为下个月的一项任务使用 C++。我了解到变量可以被溢出:具体来说,浮点类型变量不会像双精度类型那样包含尽可能多的小数。但是,我尝试了这段代码:

#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 如何保持数字的精度?

非常感谢。

【问题讨论】:

  • 演员表不是现场操作。他们返回转换后的值;他们不直接修改原件。因为你从不存储你的演员的结果,所以什么都不做。
  • float g(0.1f); 会更正确

标签: c++ c++11


【解决方案1】:

那是因为您没有将 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

【讨论】:

  • 啊,我真希望这不是一个菜鸟错误。谢谢你,无论如何。
  • @DeltaAccel 我们当中谁没有在我们的生活中犯过菜鸟错误? (;
【解决方案2】:

你没有改变 t 的值。

在下面使用这个:

 cout << static_cast<float>(t) << endl;

t = static_cast<float>(t);  
  cout << t << endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 2011-02-11
    • 2010-09-24
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多