c语言写一个求一个有理数的连分数的递归函数
时间: 2024-05-12 15:19:51 浏览: 74
C语言实现递归算法
```c
#include <stdio.h>
void continued_fraction(int numerator, int denominator) {
if (numerator == 0) {
return;
}
int quotient = denominator / numerator;
int remainder = denominator % numerator;
printf("%d ", quotient);
continued_fraction(denominator - quotient * numerator, numerator);
}
int main() {
int numerator, denominator;
printf("Enter the numerator and denominator of the rational number: ");
scanf("%d/%d", &numerator, &denominator);
printf("The continued fraction of %d/%d is: ", numerator, denominator);
continued_fraction(numerator, denominator);
printf("\n");
return 0;
}
```
这个递归函数的核心思想是利用有理数的连分数表示法,将有理数表示成一个整数加上一个真分数的形式,然后递归地求这个真分数的连分数形式。具体实现中,我们先求出整数部分(也就是商),然后递归地求出真分数的连分数形式,直到分子为0为止。在每次递归中,我们打印出商,相当于将整数部分加入到连分数的表示中。
阅读全文