为什么会出现“未处理的异常”错误,我该如何解决?

问题描述 投票:0回答:1

我正在尝试编写使用2个递归函数的代码; 'I''U'以及一个非递归函数'f'。我要达到的目标是运行递归函数I] >> “ steps1”多次,然后在此级别停止然后运行递归函数U “ step2”多次。之后,最后在函数U's迭代结束的级别上运行非递归函数f

例如:

step1 = 1

steps2 = 1然后,

我将迭代函数'I' 1次(steps1)并获得:

   I(n)= 3*I(n/2)+7*n-3  

然后,我将迭代功能U 1次(steps2)for

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 

现在将最后一个函数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; 

 }

我正在尝试编写使用2个递归函数的代码; “ I”和“ U”以及一个非递归函数“ f”。我要达到的目标是多次运行“ steps1”的递归函数,然后...

我编译并运行了程序,看起来好像堆栈溢出。函数I的递归不正确。也就是说,您的基本情况将永远无法实现。在每个被调用I的位置,您仅传递3个参数,因此counter1始终将具有默认值0。同样,总是调用I,以便steps1总是具有相同的值(根据用户输入)。因此if(counter1==steps1){永远不会为真。

针对未来问题的一些建议,当对此类问题进行故障排除时,最简单的操作之一就是在每个函数的开头添加cout。打印功能名称和参数值。另一个选择是连接调试器并设置一些断点。学习如何在C ++中使用调试器将非常非常方便。

c++ recursion stack-overflow unhandled-exception
1个回答
0
投票

我编译并运行了程序,看起来好像堆栈溢出。函数I的递归不正确。也就是说,您的基本情况将永远无法实现。在每个被调用I的位置,您仅传递3个参数,因此counter1始终将具有默认值0。同样,总是调用I,以便steps1总是具有相同的值(根据用户输入)。因此if(counter1==steps1){永远不会为真。

© www.soinside.com 2019 - 2024. All rights reserved.