gpt4 book ai didi

c++ cout << 不要在小数点前打印 '0'

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:25 32 4
gpt4 key购买 nike

我没有找到在小数点前没有“0”的情况下写入次于 1 的十进制数的解决方案。我想以这种格式显示数字:“.1”、“.2”等...

使用:

std::cout << std::setw(2) << std::setprecision(1) << std::fixed << number;

总是给我“0.1”、“0.2”等格式...

我做错了什么?感谢您的帮助

最佳答案

您需要将其转换为字符串并用于打印。如果有的话,流无法打印没有前导零的 float 。

std::string getFloatWithoutLeadingZero(float val)
{
//converting the number to a string
//with your specified flags

std::stringstream ss;
ss << std::setw(2) << std::setprecision(1);
ss << std::fixed << val;
std::string str = ss.str();

if(val > 0.f && val < 1.f)
{
//Checking if we have no leading minus sign

return str.substr(1, str.size()-1);
}
else if(val < 0.f && val > -1.f)
{
//Checking if we have a leading minus sign

return "-" + str.substr(2, str.size()-1);
}

//The number simply hasn't a leading zero
return str;
}

试一试 online !

编辑:您可能更喜欢的一些解决方案是自定义浮点类型。例如

class MyFloat
{
public:
MyFloat(float val = 0) : _val(val)
{}

friend std::ostream& operator<<(std::ostream& os, const MyFloat& rhs)
{ os << MyFloat::noLeadingZero(rhs._val, os); }

private:
static std::string noLeadingZero(float val, std::ostream& os)
{
std::stringstream ss;
ss.copyfmt(os);
ss << val;
std::string str = ss.str();

if(val > 0.f && val < 1.f)
return str.substr(1, str.size()-1);
else if(val < 0.f && val > -1.f)
return "-" + str.substr(2, str.size()-1);

return str;
}
float _val;
};

试一试 online !

关于c++ cout << 不要在小数点前打印 '0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26684939/

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