关于浮点数的十进制和整数提取以及某些特定小数点的输出,有很多问题和答案。但没有人能解决我的问题。如果有人能帮助我解决我的问题,请
我实际上是试图从浮点数中提取精确的小数部分。我试过这个:
float f=254.73;
int integer = (int)f;
float fractional = f-integer;
printf ("The fractional part is: %f", fractional);
但输出为: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);
它给了我72作为输出。但是,我想从给定的数字254.73中精确地提取73。我已经知道如何在%.2f
函数中使用printf()
来打印最多两个十进制数字。但在我的代码中,我现在不想打印这个数字。我有一些计算,其中小数部分为整数形式,即73.所以,我的问题是如何从254.73中提取小数部分,以便我可以得到精确的73作为整数来进行更多的计算?
最简单的方法是使用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;
更新:正如comment在@Sneftel中所指出的,上述建议的方法在这个答案中不会一致。
一个简单的黑客是使用round
的math.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);
输出:
254, 73
如何从浮点数中得到精确的小数部分作为整数?
试图从浮点数中提取精确的小数部分。
使用modf()
或modff()
double modf(double value, double *iptr);
float modff(float value, float *iptr);
modf
函数将参数值分解为整数和小数部分,...... C11§7.12.6.122
#include <math.h>
double value = 1.234;
double ipart;
double frac = modf(value, &ipart);
对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
参考细节:当OP使用254.73
时,这将转换为最接近的float
值,可能是254.729995727539...
。
float f = 254.73;
printf("%.30f\n", f);
// 254.729995727539062500000000000000
您可以使用sprintf和sscanf将值打印到字符串,然后提取分数。 %*d
扫描并丢弃格式化字符串的第一个整数。扫描点然后扫描分数。
#include <stdio.h>
int main( void)
{
char fp[30];
int fraction;
float f = 254.73f;
sprintf ( fp, "%.2f", f);
sscanf ( fp, "%*d.%d", &fraction);
printf ( "%d\n", fraction);
return 0;
}