gpt4 book ai didi

c++ - std::setprecision设置有效数字的数量。如何使用iomanip设置精度?

转载 作者:行者123 更新时间:2023-12-03 16:09:35 25 4
gpt4 key购买 nike

我总是发现iomanip令人困惑并且反直观。我需要帮助。
快速的互联网搜索发现(https://www.vedantu.com/maths/precision)“因此,我们将精度视为十进制数字中小数点之后的最大有效位数”(重点是我的)。这也符合我的理解。但是我编写了一个测试程序,并且:

stm << std::setprecision(3) << 5.12345678;
std::cout << "5.12345678: " << stm.str() << std::endl;
stm.str("");

stm << std::setprecision(3) << 25.12345678;
std::cout << "25.12345678: " << stm.str() << std::endl;
stm.str("");

stm << std::setprecision(3) << 5.1;
std::cout << "5.1: " << stm.str() << std::endl;
stm.str("");
输出:
5.12345678: 5.12
25.12345678: 25.1
5.1: 5.1
如果精度为3,则输出应为:
5.12345678: 5.123
25.12345678: 25.123
5.1: 5.1
显然,与浮点数有关,C++标准对“精度”的含义有不同的解释。
如果我做:
stm.setf(std::ios::fixed, std::ios::floatfield);
那么前两个值的格式正确,但最后一个为5.100
如何设置精度而不填充?

最佳答案

您可以尝试使用以下解决方法:

decltype(std::setprecision(1)) setp(double number, int p) {
int e = static_cast<int>(std::abs(number));
e = e != 0? static_cast<int>(std::log10(e)) + 1 + p : p;
while(number != 0.0 && static_cast<int>(number*=10) == 0 && e > 1)
e--; // for numbers like 0.001: those zeros are not treated as digits by setprecision.
return std::setprecision(e);
}
然后:
auto v = 5.12345678;
stm << setp(v, 3) << v;

另一个更为冗长和优雅的解决方案是创建一个像这样的结构:
struct __setp {
double number;
bool fixed = false;
int prec;
};

std::ostream& operator<<(std::ostream& os, const __setp& obj)
{
if(obj.fixed)
os << std::fixed;
else os << std::defaultfloat;
os.precision(obj.prec);
os << obj.number; // comment this if you do not want to print immediately the number
return os;
}

__setp setp(double number, int p) {
__setp setter;
setter.number = number;

int e = static_cast<int>(std::abs(number));
e = e != 0? static_cast<int>(std::log10(e)) + 1 + p : p;
while(number != 0.0 && static_cast<int>(number*=10) == 0)
e--; // for numbers like 0.001: those zeros are not treated as digits by setprecision.

if(e <= 0) {
setter.fixed = true;
setter.prec = 1;
} else
setter.prec = e;
return setter;
}
像这样使用它:
auto v = 5.12345678;
stm << setp(v, 3);

关于c++ - std::setprecision设置有效数字的数量。如何使用iomanip设置精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66690841/

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