Bry*_*yce -1 c++ floating-point
我在尝试使用std :: cout <<输出我的浮点时遇到问题
我有以下价值观:
vector2f = {-32.00234098f, 96.129380f} //takes 2 floats (x, y)
output: -32.0023:96.1294
Run Code Online (Sandbox Code Playgroud)
我在寻找的是:
output: -32.00234098:96.129380
Run Code Online (Sandbox Code Playgroud)
实际数字可能从7位小数(.0000007)到3位小数(.003)不等,因此在这种情况下设置固定的舍入数不起作用.
任何帮助都会很棒,因为我已尝试改为双打,但无济于事.
提前致谢!
有两个问题.
你需要包含<iomanip>
和使用std::setprecision
操纵器.
要获得所需的准确度,您需要使用double
s而不是float
s.
例如:
#include <iostream>
#include <iomanip>
int main()
{
auto x = -32.00234098f, y = 96.129380f;
std::cout << std::setprecision(8) << std::fixed << x << ":" << y << std::endl;
// doubles
auto a = -32.00234098, b = 96.129380;
std::cout << std::setprecision(8) << std::fixed << a << ":" << b << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
示例输出:
-32.00234222:96.12937927
-32.00234098:96.12938000
Run Code Online (Sandbox Code Playgroud)