简体   繁体   English

c ++中的cout浮点格式

[英]cout floating point format in c++

std::ostream& operator<<(std::ostream& o, const mat4& m)
{
    o << std::setprecision(6) << std::fixed << std::right;
    const int w = 8;
    for (int i = 0; i < 4; i++)
    {
        int j = 4 * i;
        o << '[' << std::setw(w) << m[j] << ',' << std::setw(w) << m[1 + j] << ',' << std::setw(w)  <<  m[2 + j] << ',' << std::setw(w) << m[3 + j] << ']' << std::endl;
    }

    return o;
}

I want to print my data as: 我想将数据打印为:

[-1.00000, 1.00000, 123.000,-23.0000]

This is what I want to achieve: 这是我要实现的目标:

  • Add a space if the negative sign doesn't exist 如果负号不存在,请添加一个空格
  • The size of the string is fixed and it only shows the most significant values 字符串的大小是固定的,并且仅显示最高有效值

I am thinking of using std::fixed or std::scientific but cannot figure out how to achieve the above formatting with iomanip. 我正在考虑使用std::fixedstd::scientific但无法弄清楚如何使用iomanip实现上述格式。 Can this even be done with iomanip or do I need to implement my own methods? 甚至可以使用iomanip完成此操作,还是需要实现自己的方法?

You want setiosflags(ios_base::showpoint) 您想要setiosflags(ios_base::showpoint)

#include <iomanip>
#include <iostream>

int main()
{
  double m[] = {-1, 1, 123, -23};
  const int w = 8;
  std::cout << std::setiosflags(std::ios_base::showpoint);
  std::cout << '[' << std::setw(w) << m[0] << ',' << std::setw(w) << m[1] << ',' << std::setw(w)  <<  m[2] << ',' << std::setw(w) << m[3] << ']' << std::endl;
}

The result is: 结果是:

[-1.00000, 1.00000, 123.000,-23.0000]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM