将Python算法翻译成C++时遇到问题

Stuck translating a Python algorithm into C++

本文关键字:遇到 问题 C++ Python 算法 翻译      更新时间:2023-10-16

我正在尝试将Python中的Fibonacci算法翻译成C++,除了语法上的某个地方出错之外,我的大部分算法都能工作。

这是我目前拥有的Python版本:

if n == 0:
    return (0, 1) *****
else:
    a, b = _fib(n // 2)
    c = a * (b * 2 - a)
    d = a * a + b * b
    if n % 2 == 0:
        return (c, d) *****
    else:
        return (d, c + d) *****

我就是这样把它翻译成C++的

int fib2(int n) {
 if (n == 0) {
    return (0, 1); *****
 }
 else {
    int a = fib2(n/2);
    int b = fib2(n/2);
    int c = a*(2*b-a);
    int d = a*a + b*b;
    if (n % 2 == 0) {
        return (c, d); *****
    }
    else {
        return (d, c + d); *****
    }
 }
}

我在错误产生的地方打了5颗星。如果我理解正确的话,在Python版本中,它将两个斐波那契数作为一对返回。然而,当我在C++中尝试相同的语法时,它会显示"预期表达式"。

我理解为什么会发生这种情况,有人知道我如何纠正我的C++代码,使其也可以返回两个Fibonacci数的元组吗?

以下是使用std::pair 的结果

#include <iostream>
#include <utility>
using namespace std;
typedef pair<int,int> myPair;
myPair fib2(int n) 
{
    if (n == 0)            return make_pair(0, 1); 
    myPair r = fib2(n/2);
    int a = r.first;
    int b = r.second;
    int c = a*(2*b-a);
    int d = a*a + b*b;
    if (n % 2 == 0)        return make_pair(c, d); 
    else                   return make_pair(d, c + d); 
}
int main()
{
    myPair result = fib2(12);
    cout << "result:" << result.first << endl;
}