【问题标题】:std::setprecision not showing trailing decimals [duplicate]std::setprecision 不显示尾随小数 [重复]
【发布时间】:2016-12-16 06:56:03
【问题描述】:

我正在尝试将双精度和整数打印为双精度。为此,我编写了以下程序:

int main()
{
    string object="1";
    std::stringstream objectString;
    objectString << std::setprecision(8) << atof(object.c_str());                
    cout<<"ObjectString="<<objectString.str()<< " "<<std::setprecision(10) <<  double(atof(object.c_str())) <<"\n";
}

我预计输出是:

ObjectString=1.0  1.0

但是,我得到的输出是:

ObjectString=1  1

有人可以建议我哪里出错了吗?

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    要强制尾随零,请使用std::fixed

    std::string object = "1";
    std::stringstream objectString;
    objectString << std::fixed << std::setprecision(8) << atof(object.c_str());                
    std::cout << "ObjectString=" << objectString.str() << " ";
    std::cout << std::fixed << std::setprecision(10) << double(atof(object.c_str())) << "\n";
    

    输出:

    ObjectString=1.00000000 1.0000000000
    

    【讨论】:

      【解决方案2】:

      强制输出始终显示小数点的方法是使用std::showpoint

      #include <iostream>
      #include <iomanip>
      
      int main() {
          double d = 1.0;
          std::cout << std::setprecision(1) << d << '\n';
          std::cout << std::setprecision(1) << std::showpoint << d << '\n';
          return 0;
      }
      
      [temp]$ ./a.out
      1
      1.
      [temp]$ 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-26
        • 2021-10-02
        相关资源
        最近更新 更多