An interview question:
Given two int N (numerator) and D (denominator), return the fraction in string. if the fraction is repeating, then display the repeating part in
For fixed point, simply multiply the numerator with 10 before dividing. For floating point, simply use division then modf to get the fractional part. In either case, convert to string then format as preferred (1 decimal).
In C you could do something generic that handles either fixed or floating point, by use of _Generic.
A simple example without any error handling:
#include
#include
#include
char* strfract_int (char* dst, int n, int d)
{
sprintf(dst, "0.%d", n*10 / d);
return dst;
}
char* strfract_double (char* dst, double n, double d)
{
double dummy;
sprintf(dst, "%.1f", modf(n/d, &dummy) );
return dst;
}
#define strfract(dst, n, d) \
_Generic((n), \
int: strfract_int, \
double: strfract_double)(dst,n,d) \
int main (void)
{
char buf [100];
puts( strfract(buf, 1, 3) );
puts( strfract(buf, 2, 5) );
puts( strfract(buf, 1.0, 3.0) );
puts( strfract(buf, 2.0, 5.0) );
}
In a rugged program, check for division against zero, the result of malloc etc etc.