如何在没有科学记数法或尾随零的情况下将浮点数输出到 cout
How to output float to cout without scientific notation or trailing zeros?
在没有科学记数法或尾随零的情况下输出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.
我不确定"最优雅的方式",但这里有一种方法。
#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;
}
如果您需要大量此类输出,您可以创建自己的I/O操纵器。 这可以说更优雅,但实现可能类似。
如果字符串操作不会伤害你的眼睛:
std::string fixedfloat(float x)
{
std::ostringstream ss;
ss << std::fixed << std::setprecision(std::cout.precision()) << x;
std::string str = ss.str();
return str.substr(0, str.find_last_not_of('0') + 1);
}
int main()
{
float b = 0.1f;
std::cout << std::setprecision(6) << fixedfloat(b);
}
或
class fixedfloat
{
public:
fixedfloat(float x) : x(x) {}
float value() const { return x; }
private:
float x;
};
ostream &operator<<(ostream &out, const fixedfloat &f)
{
ostringstream ss;
ss << fixed << setprecision(out.precision()) << f.value();
string str = ss.str();
out << str.substr(0, str.find_last_not_of('0') + 1);
return out;
}
int main()
{
float b = 0.1f;
cout << setprecision(6) << fixedfloat(b);
}
另一个像我的例子实际上输出"200",或者"200">>"2"。
这应该适用于所有内容(因为我从字符串到我使用的 val 函数)。
string fix(float in) {
string s = to_string(in);
size_t dot = s.find_first_of('.'), last = s.find_last_not_of(".0");
if (dot!=string::npos) return s.substr(0, max(dot,last+1));
else return s;
}
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在没有未定义行为的情况下,将浮点缓冲区重新用于双打
- 在不使用 * 和 / 运算符的情况下将两个浮点数相乘和除以
- 如何在不使用对象的情况下连接字符串、整数和浮点数
- 在C++中安全地重新缩放和向下投射浮点数
- 有没有办法将数字作为字符串,并在不使用浮点数或双精度数的情况下将其四舍五入到确切的位数
- 为什么在浮点比较中,最后一个小数位数为5的浮点值能给出正确的输出,而在其他情况下却不是
- 如何在没有浮点数/双精度数的情况下生成均匀和高斯分布的伪随机数
- C++ 标准库堆栈使用情况.推送浮点数组时出现问题
- 有没有什么方法可以在不丢失十进制值的情况下将浮点值转换为int值
- VS2010中的浮点内省-如何在不中断的情况下进行检查
- 如何在没有科学记数法或尾随零的情况下将浮点数输出到 cout
- 如何在 c++ 下对尾数和双精度或浮点数的指数部分进行操作(快速)
- 在哪种情况下,我可以在C++中使用==直接比较两个浮点变量
- 如何在构造函数外部分配 Boost 的情况下序列化大型错误定位浮点数组?
- 生成下一个最大或最小的可表示浮点数,而不需要位偏移
- 使用相等性对浮点数进行比较的情况
- 类中的内存使用情况 - 将双精度转换为浮点数并未按预期减少内存使用量
- 为什么C++编译器默认情况下不对整数、浮点和指针变量进行零初始化?