C++ 递归函数无限循环问题及解决方案 - f1 函数分析
C++ 递归函数无限循环问题及解决方案 - f1 函数分析
在给定的代码中,函数 f1 的递归调用没有终止条件,所以会陷入无限递归的循环中,导致程序无法结束。为了解决这个问题,你需要添加一个终止条件来停止递归调用。
问题代码
#include<iostream>
using namespace std;
int f1(long n){
int count=0;
long a1=n/2;
long a2=n%2;
long a3=n/2;
if(a1==0||a2==0||a3==0){
count++;
}
return f1(a1)+f1(a2)+f1(a3);
}
int main(){
long n;
cin>>n;
int res=f1(n);
cout<
解决方案
以下是修复后的代码:
#include<iostream>
using namespace std;
int f1(long n){
if(n == 0) {
return 1;
}
int count=0;
long a1=n/2;
long a2=n%2;
long a3=n/2;
count += f1(a1) + f1(a2) + f1(a3);
return count;
}
int main(){
long n;
cin>>n;
int res=f1(n);
cout<<res<<endl;
return 0;
}
在这个修复后的代码中,当 n 等于 0 时,递归调用停止,返回 1。这样可以保证递归调用能够终止,得到正确的结果。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pFPf 著作权归作者所有。请勿转载和采集!