【发布时间】:2013-03-08 12:30:13
【问题描述】:
我想使用 c/c++ 将大双精度数 (>1e6) 舍入到最接近但更大的浮点数。 我试过了,但我不确定它总是正确的,也许有最快的方法:
int main() {
// x is the double we want to round
double x = 100000000005.0;
double y = log10(x) - 7.0;
float a = pow(10.0, y);
float b = (float)x;
//c the closest round up float
float c = a + b;
printf("%.12f %.12f %.12f\n", c, b, x);
return 0;
}
谢谢。
【问题讨论】:
-
所以,
1.2应该变成2,对吧? -
@jrok 你从哪里得到 OP 想要舍入为整数的想法?
-
起初看起来很简单,但这确实是一个非常有趣的问题。愿意解释一下您是如何获得原始解决方案的吗?
-
但你的意思是,最接近的较大整数(如整数的数学定义,即:整数)?或类似 1.234 -> 1.24
-
@MementoMori,
float的精度不如double,因此如果您可以在double中表示100000000000000,则不能在float中这样做.例如,float中最接近的可能是100000008765440。它根本不是传统意义上的四舍五入。
标签: c++ c floating-point rounding