在获取整数double值的小数部分,而不会丢失precision [英] Getting the fractional part of a double value in integer without losing precision
问题描述
我想用precision高达4位为整数的double值的小数部分转换。但是当我这样做,我失去了precision。有什么办法让我可以得到precise价值?
i want to convert the fractional part of a double value with precision upto 4 digits into integer. but when i do it, i lose precision. Is there any way so that i can get the precise value?
#include<stdio.h>
int main()
{
double number;
double fractional_part;
int output;
number = 1.1234;
fractional_part = number-(int)number;
fractional_part = fractional_part*10000.0;
printf("%lf\n",fractional_part);
output = (int)fractional_part;
printf("%d\n",output);
return 0;
}
我期待输出为1234,但它给了1233.请建议,这样我就可以得到所需要的输出方式。我想在C语言中的解决方案。
i am expecting output to be 1234 but it gives 1233. please suggest a way so that i can get desired output. i want the solution in C language.
推荐答案
假设你希望得到一个积极的分数甚至负值,我会去用
Assuming you want to get back a positive fraction even for negative values, I'd go with
(int)round(fabs(value - trunc(value)) * 1e4)
这应该给您预期的结果 1234
。
如果你不圆,只是截断值
If you do not round and just truncate the value
(int)(fabs(value - trunc(value)) * 1e4)
(基本上是一样的你原来的code),你会用意想不到的结果 1233
为 1.1234结束 - 1.0 = 0.12339999999999995
双precision。
(which is essentially the same as your original code), you'll end up with the unexpected result 1233
as 1.1234 - 1.0 = 0.12339999999999995
in double precision.
如果不使用 ROUND()
,你还可以得到预期的结果,如果你改变操作的顺序,以
Without using round()
, you'll also get the expected result if you change the order of operations to
(int)(fabs(value * 1e4 - trunc(value) * 1e4))
如果值
的组成部分,是足够大的,浮点不准将再次踢当然的。
If the integral part of value
is large enough, floating-point inaccuracies will of course kick in again.
您也可以使用 MODF()
而不是 TRUNC()
大卫指出,这可能是最好的方法尽可能浮点精度云:
You can also use modf()
instead of trunc()
as David suggests, which is probably the best approach as far as floating point accuracy goes:
double dummy;
(int)round(fabs(modf(value, &dummy)) * 1e4)
这篇关于在获取整数double值的小数部分,而不会丢失precision的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!