对于用户输入的2个数字x
和n
,我的代码需要查找由以下公式递归定义的Hn(x):
我正在尝试实现该函数的递归版本和迭代版本。但是我认为我的理解是错误的,因为我的代码由于H(n)和H [n]的错误而无法编译:
#include "pch.h"
#include <iostream>
int H(int n, int x) //function for recursion
{
if (n < 0) return -1;
else if (n == 0) return 1;
else if (n == 1) return 2 * x;
return 2 * x * H(n) * x - 2 * n * H(n - 1) * x;
}
int H1(int n, int x) //function for Iterator
{
int *H1 = new int[n + 1];
H[0] * x = 1;
H[1] * x = 2 * x;
for (int i = 0; i <= n; i++)
{
H[i] * x = 2 * x * H[n] * x - 2 * n * H[n - 1] * x;
}
return H1(n) * x;
}
int main()
{
int n, x;
std::cout << "Enter the number n: ";
std::cin >> n;
std::cout << "Enter the number x: ";
std::cin >> x;
std::cout << "Rec = " << H[n] * x std::endl;
std::cout << "Iter = " << H1[n] * x std::endl;
}
这很令人困惑,对此我深表歉意,因为我对功能完全陌生。
我已经设法用斐波那契数列来做到这一点。在这里,我只为函数f(x)
使用了一个参数f(int n){... }
,但是在这里我对函数H(int n, int x)
中的两个参数有些困惑,其中n
是H
,而x
是整数。
答案 0 :(得分:0)
是的,您需要将以数学方式索引的函数转换为具有2个参数的函数。
除了索引中的某些偏移之外,递归版本几乎还可以:
int H(int n, int x) // recursive version
{
if (n <= 0)
return -1;
else if (n == 1)
return 1;
else if (n == 2)
return 2 * x;
else
return 2 * x * H(n-1, x) - 2 * n * H(n - 2, x); // shift n+1, n n-1 to n, n-1 n-2
}
您的迭代版本需要重新编写,因为您应尽可能将其编写为循环,而不必兑现不再需要的值。例如:
int Hi(int n, int x) //iterative version
{
if (n <= 0)
return -1;
else if (n == 1)
return 1;
int am2 = 1; // start for for n-2
int am1 = 2*x; // start for n-1
if (n == 2)
return am1;
int am;
for (int i=3; i<=n; i++) {
am = 2*x*am1 - 2*i*am2; // calculate Hn from Hn-1 and Hn-2
//prepare next interation
am2=am1;
am1=am;
}
return am;
}
答案 1 :(得分:0)
您写道:
int H(int n, int x) //function for recursion
{
if (n < 0) return -1;
else if (n == 0) return 1;
else if (n == 1) return 2 * x;
return 2 * x * H(n) * x - 2 * n * H(n - 1) * x;
}
您距离正在运行的程序不远。删除该H1
函数。让我们看看:
int H(int n, int x)
{
switch(n)
{
// H_0(x) = 1
case 0: return 1;
// H_1(x) = 2x
case 1: return 2 * x;
// H_{n+1}(x) = 2x H_n(x) - 2n H_{n - 1}(x)
default:
return 2*x*H(n-1, x) - 2*(n-1)*H(n-2, x);
}
}
窍门部分是,意识到n
中的H_{n+1}(x) = 2x H_n(x) - 2n H_{n - 1}(x)
和return 2*x*H(n-1, x) - 2*(n-1)*H(n-2, x);
中的H
并不相同,它们相差一个。
现在,您只需要处理用户I / O并使用用户输入来调用{{1}}函数。