连分式分式

2023-09-11 06:08:24 作者:烈酒暖心

下面是我做到了与小数和它的作品:

Here's how I did it with decimals and it works:

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;
}

我的问题是你怎么做同样的事情,使用整数小数运算:一个分子和分母。我需要非递归做到这一点,一切都应该在函数中不包含任何额外的东西做的工作要做。我不认为这是很难一旦你知道怎么做,但对我来说这是不可能的,我不能想象它,我AP preciate任何指导......谢谢你。

My question is how do you do the same thing with fractional arithmetic using ints: a numerator and a denominator. I need to do it nonrecursively and everything should be done within the function without including anything extra to do it. I don't think it's that hard once you know how to do it but to me it's impossible I can't visualize it, I appreciate any guidance... thank you.

推荐答案

如果我理解连分数正确的,你不需要计算的分子和分母的最大公约数。

If I understand continued fractions correctly, you don't need to compute the GCD of the numerator and the denominator.

下面的程序做这项工作:

The following program does the job:

#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;
}

运行程序的输出:

Output of running the program:


Numerator: 415, Denominator: 93