坚持将 Python 算法翻译成 C++
Stuck translating a Python algorithm into C++
我正在尝试将 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 版本中,它是 return 将两个斐波那契数作为一对。但是,当我在 C++ 中尝试相同的语法时,它显示 "Expected expression"。
我明白为什么会这样,有谁知道我如何更正我的 C++ 代码,以便它也可以 return 两个斐波那契数的元组?
以下是使用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;
}
我正在尝试将 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 版本中,它是 return 将两个斐波那契数作为一对。但是,当我在 C++ 中尝试相同的语法时,它显示 "Expected expression"。
我明白为什么会这样,有谁知道我如何更正我的 C++ 代码,以便它也可以 return 两个斐波那契数的元组?
以下是使用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;
}