作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我总是发现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/
如何在 C++ 中进行涉及有效数字的数学运算?我希望它能正确处理化学和物理实验的测量数据。一个例子:65/5 = 10。我需要去掉不需要的小数位并将一些数字替换为 0。 谢谢! 最佳答案 这应该可以满
这个任务看起来很简单 - 在输入时我得到测试数量 (numOfTests),然后是两个数字 (downBorder, upBorder) 和我必须找出这些数字(downBorder、upBorder)
如果我有 double (234.004223) 等,我想在 C# 中将其四舍五入为 x 位有效数字。 到目前为止,我只能找到舍入到 x 位小数的方法,但是如果数字中有任何 0,这只会删除精度。 例如
我是一名优秀的程序员,十分优秀!