在C++中输出浮点数的最优雅方法是什么,没有科学记数法或尾随零?
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.
Run Code Online (Sandbox Code Playgroud)
我不确定"最优雅的方式",但这是一种方式.
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果需要大量此类输出,也可以创建自己的I/O操纵器.这可以说更优雅,但实施可能类似.
| 归档时间: |
|
| 查看次数: |
4031 次 |
| 最近记录: |