gpt4 book ai didi

c++ - 如何将 float .1 流式传输为 .1 而不是 0.1

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:05:42 24 4
gpt4 key购买 nike

std::ostringstream oss;
oss << std::setw(10);
oss << std::setfill(' ');
oss << std::setprecision(3);
float value = .1;
oss << value

我可以检查值是否 < 1,然后找到前导零并将其删除。不是很优雅。

最佳答案

I can check if value < 1 and then find the leading zero and remove it. Not very elegant.

同意,但这是您必须做的,而无需在语言环境中乱搞来定义您自己的 ostream::operator<<(float) 版本。 (你不想做这种事。)

void float_without_leading_zero(float x, std::ostream &out) {
std::ostringstream ss;
ss.copyfmt(out);
ss.width(0);
ss << x;
std::string s = ss.str();
if (s.size() > 1 && s[0] == '0') {
s.erase(0);
}
out << s;
}

关于c++ - 如何将 float .1 流式传输为 .1 而不是 0.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4889218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com