持续的分数

Continued Fractions

本文关键字:      更新时间:2023-10-16

我是这样处理小数的:

double continuedFractionDecimal(int a[], int size)
{
    double fraction = a[size - 1];  
    for(int i = size - 2; i >= 0; i--)
    {
        fraction = a[i] + 1/fraction;
    }
    return fraction;
}

我的问题是你如何用整数做同样的事情:分子和分母。我需要以非递归的方式来做,所有的事情都应该在函数内完成,而不包括任何额外的东西。我不认为一旦你知道怎么做就很难了,但对我来说,这是不可能的,我无法想象它,我感谢任何指导……谢谢你。

如果我对连分式理解正确的话,你不需要计算分子和分母的GCD

下面的程序完成这项工作:

#include <iostream>
#include <utility>
std::pair<int, int> getFraction(int a[], int size)
{
   int n = 1;
   int d = a[size-1];
   for(int i = size - 2; i >= 0; i--)
   {
      int nextd = d*a[i] + n;
      n = d;
      d = nextd;
   }
   // When we are done, d is the numerator and n is the denominator.
   return std::make_pair(d, n);
}
int main()
{
   int a[] = {4, 2, 6, 7};
   int size = sizeof(a)/sizeof(a[0]);
   std::pair<int, int> f = getFraction(a, size);
   std::cout
      << "Numerator: " << f.first
      << ", Denominator: " << f.second << std::endl;
}

运行程序的输出:

<>之前分子415,分母93
相关文章:
  • 没有找到相关文章