【发布时间】:2020-08-20 20:33:10
【问题描述】:
我正在尝试编写一个使用 2 个递归函数的代码; 'I' 和 'U' 以及一个非递归函数 'f'。我想要实现的是多次运行递归函数 I "steps1" 然后在这个级别停止然后运行 递归函数 U "steps2" 多次。 之后,最后在函数U的迭代结束的层级运行非递归函数f。
例如:
然后让 steps1=1 和 steps2=1,
我将迭代函数 'I',1-time(steps1) 并得到:
I(n)= 3*I(n/2)+7*n-3
然后,我将迭代函数 U, 1-time(steps2) for n/2 em> 值。然后,插入它而不是 I(n/2),因此我将计算:
I(n)= 3*[U(n/2)]+7*n-3= 3*[2*U(n/6)+2*(n/2)-9] = 3*2*U(n/6)+3*2*(n/2)-3*9
现在将最后一个函数 f(n/6) 插入到这个方程中:
3*2*U(n/6)+3*2*(n/2)-3*9=3*2*f(n/6)+3*2*(n/2)-3*9
因为 f 是非递归的,所以这会给我结果。
当我运行我的代码时,我得到“未处理的异常”错误。有人可以帮我找出这个错误的原因吗?我的代码在某个地方错了吗?有人可以帮我解决这个问题吗?我不确定我的代码是否也完全符合我的要求?
#include<stdlib.h>
#include<bits/stdc++.h>
using namespace std;
int f(int n)
{
return (n-1)*(n-1);
}
/* step2 many iteration of the function U and then function f */
int U(int n , int steps2, int counter2=0)
{
if(counter2==steps2){
return f(n);
}
return 2*U(n/3, steps2, counter2+1)+2*n-9;
}
/* step1 many iteration of the function I and then function U*/
int I(int n , int steps1,int steps2, int counter1=0, int counter2=0)
{
if(counter1==steps1){
return U(n,steps2,counter2);
}
return 3*I(n/2, steps1, counter1+1)+7*n-3;
}
int main(){
int n, steps1,steps2;
cout<< " Enter 'n' value which is divisable by both 2 and 3"<<"\n";
cin>>n;
cout<< " Enter iteration count for I"<<"\n";
cin>>steps1;
cout<< " Enter iteration count for U"<<"\n";
cin>>steps2;
cout<< " result:" << I(n,steps1,steps2)<<"\n";
getchar();
return 0;
}
【问题讨论】:
-
在询问与代码相关的问题时,始终建议为您使用的特定语言添加标签。它有助于将您的问题呈现在可以回答的人面前。
标签: c++ recursion stack-overflow unhandled-exception