将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版本中,它将两个斐波那契数作为一对返回。然而,当我在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;
}
相关文章:
- 编译包含字符串的代码时遇到问题
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- 从其他类访问类时遇到问题
- 使用静态成员声明类时遇到问题
- C++ 填充数组时遇到问题
- 在将字符串放入字符串向量时遇到问题?
- 余数除法和不允许除以零 (c++) 时遇到问题
- 我在C++中使用 getline() 函数时遇到问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 在我的四叉树实现中遇到问题
- 在 c++ 中循环遍历数组时遇到问题
- 使用 MinGW 在 Windows 上构建 GLEW 时遇到问题
- 编译 Cilk Plus 程序时遇到问题
- 存储另一个函数返回的布尔数组时遇到问题
- 我在 OpenGL 中显示图像时遇到问题
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组
- 在 for 循环中更新两个变量时遇到问题C++
- 为什么我的程序在打开网络设备时遇到问题
- 在 Tensorflow C++ 中使用 FIFOQueue 时遇到问题
- 为什么我在虚幻引擎中的多态性和接口方面遇到问题?