Joe Wright wrote:
Ivan Leo Puoti wrote:
How can I get a function to return the .xxx part of a floating point
number?
Subtract the integral part and return the difference.
double frac(double d) {
int i = d;
return d - i;
}
Sorry, but no:
#include <limits.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
/* Joe Wright's contribution */
double frac(double d)
{
int i = d;
return d - i;
}
int main(void)
{
double fpnum;
double fpart;
double ipart;
printf("Ivan Leo Puoti asked:\n"
" \"How can I get a function to return the\n"
" .xxx part of a floating point number?\"\n"
"Joe Wright claimed:\n"
" \"Subtract the integral part and return\n"
" the difference.\"\n" "Let's test his code.\n"
"*Warning* The results of this test will vary with\n"
" the implementation.\n\n");
fpnum = INT_MAX;
printf("INT_MAX = %d, fpnum = %.*g\n", INT_MAX, DBL_DIG, fpnum);
fpnum += 3.37;
printf("fpnum modified to %.*g\n", DBL_DIG, fpnum);
fpart = frac(fpnum);
printf("Joe Wright's code claims the fractional part is %g\n"
" (and tells us nothing of the integral part.)\n\n", fpart);
fpart = modf(fpnum, &ipart);
printf("modf returns the fractional part as %g\n"
" and the integral part as %.*g\n", fpart, DBL_DIG, ipart);
return 0;
}
Ivan Leo Puoti asked:
"How can I get a function to return the
.xxx part of a floating point number?"
Joe Wright claimed:
"Subtract the integral part and return
the difference."
Let's test his code.
*Warning* The results of this test will vary with
the implementation.
INT_MAX = 2147483647, fpnum = 2147483647
fpnum modified to 2147483650.37
Joe Wright's code claims the fractional part is 4.29497e+09
(and tells us nothing of the integral part.)
modf returns the fractional part as 0.37
and the integral part as 2147483650