1 题意。
2 分析。
第一个Fun函数, OJ返回Runtime Error,我以为是递归溢出了,写了第二个Fun,发现前者也有可能是数组越界,后来证明,是数组越界。
So,如果要判断,就在数组赋值前进行判断,防止越界。
#include<iostream>
#include <stdio.h>
#include <algorithm>
#include <math.h>
using namespace std;
const int maxn=1e4;
int poor_num[maxn+10];
int fenjie(int x){
int gewei;
int sum=0;
while(x/10>0){
gewei=x%10;
x/=10;
sum+=gewei;
}
sum+=x;
return sum;
}
void Fun(int x){
int hebing=x+fenjie(x);
//poor_num[hebing]=x;
if(hebing<=maxn){
poor_num[hebing]=x;
Fun(hebing);
}
}
/*
void Fun(int x){
int hebing=x+fenjie(x);
while(hebing<=maxn){
poor_num[hebing]=x;
x=hebing;
hebing=x+fenjie(x);
}
}
*/
int main()
{
for(int i=1;i<=maxn;i++){
poor_num[i]=i;
}
for(int i=1;i<=maxn;i++){
if(poor_num[i]==i)
Fun(i);
}
for(int i=1;i<=maxn;i++){
if(poor_num[i]==i){
cout<<i<<endl;
}
}
return 0;
}
本文探讨了一个关于递归函数导致数组越界的问题,并提供了解决方案。通过对递归调用过程的调整,在每次递归之前加入边界检查,有效避免了越界错误的发生。
1万+

被折叠的 条评论
为什么被折叠?



