/*---------------------------------------------------------------------- File : frac.c Contents: print a fraction with an arbitrary number of decimals Author : Christian Borgelt History : 19.01.1998 file created ----------------------------------------------------------------------*/ #include #include /*---------------------------------------------------------------------- Functions ----------------------------------------------------------------------*/ int printfrac (int p, int q, int n) { /* --- print a fraction p/q with an */ /* arbitrary number of decimals */ int c; /* character counter */ c = printf("%i", p /q); /* print integer part of fraction */ if (n <= 0) return c; /* if no decimals requested, abort */ c += printf("."); /* print decimal point */ while (--n >= 0) { /* while not all decimals printed */ p = (p %q) *10; /* compute the remainder of p/q, */ c += printf("%i", p /q); /* multiply it by 10 to obtain the */ } /* next digit, and print the digit */ return c; /* return number of printed chars */ } /* printfrac() */ /*---------------------------------------------------------------------- For an explanation of this function see exc1-6.tex/exc1-c6.ps. ----------------------------------------------------------------------*/ int main (int argc, char *argv[]) { /* --- main function */ int p, q; /* numerator and denominator */ int n; /* number of decimal places */ if (argc != 4) { /* if wrong number of arguments given */ printf("usage: %s p q n\n", argv[0]); printf("print the fraction p/q with n decimal places\n"); return 0; /* print a usage message */ } /* and abort the program */ p = atoi(argv[1]); /* convert command line */ q = atoi(argv[2]); /* arguments to */ n = atoi(argv[3]); /* integer numbers */ if (p/q < 0) printf("-"); /* print a sign, if necessary */ printfrac(abs(p), abs(q), n); /* print fraction */ printf("\n"); /* terminate output line */ return 0; /* return 'ok' */ } /* main() */