【问题标题】:Why do I get "unhandled exception" error and how can I fix it?为什么我会收到“未处理的异常”错误,我该如何解决?
【发布时间】:2020-08-20 20:33:10
【问题描述】:

我正在尝试编写一个使用 2 个递归函数的代码; 'I''U' 以及一个非递归函数 'f'。我想要实现的是多次运行递归函数 I "steps1" 然后在这个级别停止然后运行 ​​递归函数 U "steps2" 多次。 之后,最后在函数U的迭代结束的层级运行非递归函数f

例如:

然后让 steps1=1steps2=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


【解决方案1】:

我编译并运行了您的程序,看起来您遇到了堆栈溢出。函数I 的递归不正确。即永远不会达到您的基本情况。在每个调用I 的位置,您只传递3 个参数,因此counter1 的值始终为0,即默认值。此外,I 总是被调用,使得steps1 总是具有相同的值(来自用户的输入)。所以if(counter1==steps1){ 永远不会是真的。

对未来问题的一些建议,在解决此类问题时,您可以做的最简单的事情之一就是在每个函数的开头添加cout。打印函数名称和参数值。另一种选择是连接调试器并设置一些断点。学习如何在 C++ 中使用调试器会非常方便。

【讨论】:

  • 非常感谢我刚刚修复了您指出代码的确切问题区域。似乎我忘记为函数 I 输入所有五个参数。当我调用 I(n, steps1, steps2,counter1+1, counter2) 而不是 I(n, steps1,counter1+1) 它刚刚解决了。你是通过调试得到的吗?你能举一个你提到的函数 I 的 cout 方法的例子吗?再次感谢:)
猜你喜欢
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
相关资源
最近更新 更多