本文介绍了如何在没有科学计数法或尾随零的情况下将浮点数输出到cout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中没有科学计数法或尾随零的输出浮点数的最优雅方法是什么?

What is the most elegant way to output a floating point number in C++ with no scientific notation or trailing zeros?

float a = 0.000001f;
float b = 0.1f;

cout << "a: " << a << endl;     //  1e-006 terrible, don't want sci notation.
cout << "b: " << b << endl;     //  0.1 ok.

cout << fixed << setprecision(6);
cout << "a: " << a << endl;     //  0.000001 ok.
cout << "b: " << b << endl;     //  0.100000 terrible, don't want trailing zeros.


推荐答案

我不确定最优雅的方式

I am not sure about the "most elegant way" but here's one way.

#include <iostream>
#include <iomanip>
#include <sstream>

using namespace std ;
string fix( float x, int p )
{
    ostringstream strout ;
    strout << fixed << setprecision(p) << x ;
    string str = strout.str() ;
    size_t end = str.find_last_not_of( '0' ) + 1 ;
    return str.erase( end ) ;
}


int main()
{
    float a = 0.000001f ;
    float b = 0.1f ;

    cout << "a: " << fix( a, 6 ) << endl;     //  0.000001 ok.
    cout << "b: " << fix( b, 6 ) << endl;     //  0.1 ok.

   return 0;
}

您也许可以,如果您需要大量此类输出的话。可以说这比较优雅,但实现方式可能相似。

You could perhaps create your own I/O manipulator if you need to to a lot of this kind of output. That is arguably more elegant, but the implementation could be similar.

这篇关于如何在没有科学计数法或尾随零的情况下将浮点数输出到cout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 17:29