![](/img/trans.png)
[英]Why do I keep getting this error: exception Unhandled : Unhandled exception thrown: read access violation. this was 0x4
[英]Why do I get “unhandled exception” error and how can I fix it?
我正在尝试编写一个使用 2 个递归函数的代码; 'I'和'U'以及一个非递归 function 'f' 。 我想要实现的是多次运行递归 function I “steps1”,然后在此级别停止,然后多次运行递归函数 U “steps2” 。 之后,最后在 function U 的迭代结束的级别运行非递归 function f 。
例如:
那么让steps1 = 1和steps2 =1 ,
我将迭代 function 'I' ,1次(steps1)并得到:
I(n)= 3*I(n/2)+7*n-3
然后,我将迭代函数U , 1-time(steps2)以获得n/2值。 然后,插入它而不是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
现在将最后一个 function 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;
}
我编译并运行了你的程序,看起来你遇到了堆栈溢出。 function 的递归I
不正确。 即永远不会达到您的基本情况。 在I
被称为的每个位置,您只传递 3 个参数,因此counter1
的值始终为 0,即默认值。 此外, I
总是被称为steps1
总是具有相同的值(来自用户的输入)。 所以if(counter1==steps1){
永远不会是真的。
对未来问题的一些建议,在解决此类问题时,您可以做的最简单的事情之一就是在每个 function 的开头添加一个cout
。 打印 function 名称和参数值。 另一种选择是连接调试器并设置一些断点。 学习如何使用带有 C++ 的调试器会非常非常方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.