convert fraction into string and also insert [] for repeating part

后端 未结 3 1311
抹茶落季
抹茶落季 2021-01-25 14:01

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

3条回答
  •  一个人的身影
    2021-01-25 14:26

    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.

提交回复
热议问题