双数输出被截断

Double numbers output gets truncated

我遇到一个问题,我需要使用基本的 C++ 输出系统(例如 iostream 或 sstream)打印一些双精度值,并且这个值不知何故被截断了很多。 例如:

  double a = 283752.24234;
  std::cout << 283752.24234 << std::endl;
  std::cout << a << std::endl;

两个输出都是 283752

为什么会发生这种情况,我该怎么做才能获得任何双精度值的完整输出?

Why is this happening ...

那是因为 default precision 是 6,因此只呈现最前面的 6 位数字 283752

... and what can I do to get complete output of any double value?

  1. 第一个选项是使用 std::setprecision() I/O 操纵器使用更大的 precision 值:

    #include <iostream>  
    #include <iomanip>
    
    int main(){
        double a = 283752.24234;
    
        std::cout << std::setprecision(12) <<  283752.24234 << std::endl;
        std::cout << std::setprecision(12) <<  a << std::endl;
    }
    

    Live Demo

  2. 第二个选项是使用 std::fixed I/O 操纵器显示小数点后的值:

    #include <iostream>  
    #include <iomanip>
    
    int main(){
        double a = 283752.24234;
    
        std::cout << std::fixed <<  283752.24234 << std::endl;
        std::cout << std::fixed <<  a << std::endl;
    }
    

    Live Demo

输出:

283752.242340
283752.242340