如何从浮点数中得到精确的小数部分作为整数?

Rak*_*lam 6 c floating-point

关于浮点数的十进制和整数提取以及某些特定小数点的输出,有很多问题和答案.但没有人能解决我的问题.如果有人能帮助我解决我的问题,请

我实际上是试图从浮点数中提取精确的小数部分.我试过这个:

float f=254.73;

int integer = (int)f;
float fractional = f-integer;

printf ("The fractional part is: %f", fractional);
Run Code Online (Sandbox Code Playgroud)

但输出为:0.729996.出于这个原因,当我这样做时:

float f=254.73;

int integer = (int)f;
float fractional = f-integer;
int fractional_part_in_integer = ((int)(f*100)%100);

printf ("The value is: %d", fractional_part_in_integer);
Run Code Online (Sandbox Code Playgroud)

它给了我72作为输出.但是,我想从给定的数字254.73中精确地提取73.我已经知道%.2fprintf()函数期间如何使用打印最多两个十进制数字.但在我的代码中,我现在不想打印这个数字.我有一些计算,其中小数部分为整数形式,即73.所以,我的问题是如何从254.73中提取小数部分,以便我可以得到精确的73作为整数来进行更多的计算?

希望,我能让每个人都理解.

chu*_*ica 10

如何从浮点数中得到精确的小数部分作为整数?

试图从浮点数中提取精确的小数部分.

使用modf()modff()

double modf(double value, double *iptr);
float modff(float value, float *iptr);
Run Code Online (Sandbox Code Playgroud)

这些modf函数将参数值分解为整数和小数部分,......
C11§7.12.6.122

#include <math.h>

double value = 1.234;
double ipart;
double frac = modf(value, &ipart);
Run Code Online (Sandbox Code Playgroud)

对OP的需求更好的方法可能是首先舍入一个缩放值,然后再回到整个和小数部分.

double value = 254.73;
value = round(value*100.0);

double frac = fmod(value, 100);  // fmod computes the floating-point remainder of x/y.
double ipart = (value - frac)/100.0;

printf("%f %f\n", ipart, frac);
254.000000 73.000000
Run Code Online (Sandbox Code Playgroud)

参考细节:当OP使用时254.73,将其转换为最接近的float254.729995727539....

float f = 254.73;
printf("%.30f\n", f);
// 254.729995727539062500000000000000
Run Code Online (Sandbox Code Playgroud)

  • 这不会产生OP已经得到的相同结果吗? (2认同)

hac*_*cks 0

最简单的方法是ceil使用<math.h>.
float数字254.73可以转换为254.7299957275390625000000.
f-integer会给0.7299957275390625000000
现在将其乘以100并使用ceil函数得到不小于的最小整数值72.99957275390625000000

int fractional_part_in_integer = ((int)ceil(fractional*100)) % 100;
Run Code Online (Sandbox Code Playgroud)

更新:正如@Sneftel评论所指出的,这个答案中上述建议的方法不会一致地工作。

一个简单的技巧是使用round函数 frommath.h进行四舍五入f,然后提取小数部分

float f=254.73;

int int_part = (int)f;
float fractional = round(f*100)/100 - int_part;
int fractional_part_in_integer = (int)(fractional*100);

printf("%d, %d\n ", int_part, fractional_part_in_integer);
Run Code Online (Sandbox Code Playgroud)

输出:

254, 73
Run Code Online (Sandbox Code Playgroud)

  • @黑客 是吗?尝试[这个](https://ideone.com/yeay8O)。“ceil”和“floor”都不会一致地工作,因为该值可能略低于 0.01 的倍数,也可能略高于 0.01。 (3认同)
  • @Sneftel;你是对的。我更新了我的答案。现在已经[修复](https://ideone.com/wDuXan)。 (3认同)