c++ - 连分数

标签 c++ algorithm debugging loops formula

这是我使用小数的方法,它的工作原理是:

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

我的问题是如何使用整数(分子和分母)对小数算术做同样的事情。我需要以非递归方式执行此操作,并且所有操作都应在函数内完成,而不包含任何额外的操作。我不认为一旦你知道怎么做就那么难,但对我来说,我不可能无法想象它,我感谢任何指导......谢谢。

最佳答案

如果我明白的话continued fractions正确地,您不需要计算分子和分母的 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;
}

运行程序的输出:

Numerator: 415, Denominator: 93

关于c++ - 连分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23556249/

相关文章:

c++ - SQL_TXN_SERIALIZABLE 优于 DB2 和 C++ 中的 SQL_TXN_REPEATABLE_READ

c++ - 作为友元的运算符重载

algorithm - 凸包算法修正问题

algorithm - 线程 I/O 重新排序缓冲区的标准术语?

python - 使用可变延迟打印函数调用/Python

c++ - 具有动态数组分配的 OpenMP 嵌套循环

c# - "Unable to find an entry point named [function] in dll"(c++到c#类型转换)

php - 简单的 Javascript 加密,PHP 使用共享 key 解密

.net - TryCast 在 DirectCast 工作的地方失败 (.NET 4.0)

haskell - 调试 haskell 代码的好方法是什么?