D
David Marsh
The program calculates the continued fraction representation of the input:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
double diff, n, r, i;
if(argc != 2) exit(EXIT_FAILURE);
n = strtod(argv[1], NULL);
printf("\n [");
while(1)
{
i = (int)n;
printf(" %.f", i);
diff = n - i;
r = 1 / diff;
if(r is a whole number) /* ??? */
{
printf(" %.f", r);
break;
}
n = r;
}
printf("]\n");
return 0;
}
In the while() loop, I want to test whether r is a whole number. If it
is, it is the last denominator of the continued fraction and I'm done.
Incredibly, I was not able to do this in any straighforward way. For
example, if(r == (int)r) didn't work. I finally kludged it by writing a
function that counts the significant decimal digits in a real number,
but there has got to be a better way. How would you solve the problem?
(And, yes, I realize that if the input is irrational the program doesn't
terminate.)
David
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
double diff, n, r, i;
if(argc != 2) exit(EXIT_FAILURE);
n = strtod(argv[1], NULL);
printf("\n [");
while(1)
{
i = (int)n;
printf(" %.f", i);
diff = n - i;
r = 1 / diff;
if(r is a whole number) /* ??? */
{
printf(" %.f", r);
break;
}
n = r;
}
printf("]\n");
return 0;
}
In the while() loop, I want to test whether r is a whole number. If it
is, it is the last denominator of the continued fraction and I'm done.
Incredibly, I was not able to do this in any straighforward way. For
example, if(r == (int)r) didn't work. I finally kludged it by writing a
function that counts the significant decimal digits in a real number,
but there has got to be a better way. How would you solve the problem?
(And, yes, I realize that if the input is irrational the program doesn't
terminate.)
David