【发布时间】:2022-07-26 07:46:41
【问题描述】:
我想将一个数字四舍五入到小数点后 10 位,但它返回 '6.75677',虽然它可以返回 '6.7567653457'
#include <iostream>
#include <cmath>
using namespace std;
double rounded(double number, int N)
{
return round(number * pow(10, N)) / pow(10, N); // i've chanched float to double
}
int main()
{
double value = 6.756765345678765;
cout << rounded(value, 10)
}
我希望看到一个函数返回四舍五入的数字
坦率地说,我会在 python 中看到函数“round”的替代方法
print(round(6.756765345678765, 10))
【问题讨论】:
-
A
float首先“没有”小数点后 10 位四舍五入。它不能精确地表示值以获取该信息 - 两个“相邻”有效float值之间的最小差异远大于 10^-10。 (别介意任何类型的数字根本就没有“有”数字;这是一个单独的主题。) -
我也尝试过 double 类型,但还是不行。那么,如何以完美的精度对数字进行四舍五入呢?
-
“准确无误” 浮点数是个难题