Hi,
I want to write a function that coverts a double number into its rational form. For example if the input number in 4.33 I must get numerator = 433 and denominator = 100.
Here is something I tried, it doesn't work because of floating point inaccuracy :
void ToRational( double d, int &numerator, int &denominator )
{
int n;
double dummy;
// Get the integral part
numerator = (int) num;
// Get the fractional part
double frac = modf( num, &dummy );
denominator = 1;
while( frac != 0.0 ) // This comparision will never work
{
frac *= 10;
denominator *= 10;
n = (int) frac;
frac = modf( num, &dummy );
numerator = numerator*10 + n;
}
}
Is there a solution?