C++ 递归导致段错误?
C++ recursion causing segfault?
今天我让我的学生写了这段代码,它出现了段错误,我不太明白为什么。问题是为数字的英语发音计算字母。它是最早的欧拉计划问题之一。递归有什么问题吗?
#include<iostream>
using namespace std;
int dlugosc(int x)
{
if(x == 1) return 3;
if(x == 2) return 3;
if(x == 3) return 5;
if(x == 4) return 4;
if(x == 5) return 4;
if(x == 6) return 3;
if(x == 7) return 5;
if(x == 8) return 5;
if(x == 9) return 4;
if(x == 10) return 3;
if(x == 11) return 6;
if(x == 12) return 6;
if(x == 13) return 7;
if(x == 14) return 8;
if(x == 15) return 7;
if(x == 16) return 7;
if(x == 17) return 9;
if(x == 18) return 8;
if(x == 19) return 8;
if(x == 20) return 6;
if(x == 21) return 10;
if(x == 22) return 10;
if(x == 30) return 6;
if(x == 40) return 6;
if(x == 50) return 5;
if(x == 60) return 5;
if(x == 70) return 7;
if(x == 80) return 6;
if(x == 90) return 6;
if(x == 100) return 11;
if(x == 200) return 11;
if(x == 300) return 13;
if(x == 400) return 12;
if(x == 500) return 12;
if(x == 600) return 11;
if(x == 700) return 13;
if(x == 800) return 13;
if(x == 900) return 12;
if(x < 100) return dlugosc(x-x%10) + dlugosc(x%10);
if(x < 1000) return dlugosc(x-x%100) + dlugosc(x-x%10) + dlugosc(x%10) + 3;
if(x == 1000) return 11;
}
int main()
{
int ile = 0;
for(int i=1; i<=1000; i++)
{
ile += dlugosc(i);
}
cout << ile;
return 0;
}
输入 x=110
不会退出递归。您可以通过 gdb
或手动快速检查:
if(x < 1000) return dlugosc(x-x%100) + dlugosc(x-x%10) + dlugosc(x%10) + 3;
因为 x - x%10
是 x
如果 x
可以被 10
整除,第二项 (dlugosc(x-x%10)
) 将无限递归 x = 110
.
今天我让我的学生写了这段代码,它出现了段错误,我不太明白为什么。问题是为数字的英语发音计算字母。它是最早的欧拉计划问题之一。递归有什么问题吗?
#include<iostream>
using namespace std;
int dlugosc(int x)
{
if(x == 1) return 3;
if(x == 2) return 3;
if(x == 3) return 5;
if(x == 4) return 4;
if(x == 5) return 4;
if(x == 6) return 3;
if(x == 7) return 5;
if(x == 8) return 5;
if(x == 9) return 4;
if(x == 10) return 3;
if(x == 11) return 6;
if(x == 12) return 6;
if(x == 13) return 7;
if(x == 14) return 8;
if(x == 15) return 7;
if(x == 16) return 7;
if(x == 17) return 9;
if(x == 18) return 8;
if(x == 19) return 8;
if(x == 20) return 6;
if(x == 21) return 10;
if(x == 22) return 10;
if(x == 30) return 6;
if(x == 40) return 6;
if(x == 50) return 5;
if(x == 60) return 5;
if(x == 70) return 7;
if(x == 80) return 6;
if(x == 90) return 6;
if(x == 100) return 11;
if(x == 200) return 11;
if(x == 300) return 13;
if(x == 400) return 12;
if(x == 500) return 12;
if(x == 600) return 11;
if(x == 700) return 13;
if(x == 800) return 13;
if(x == 900) return 12;
if(x < 100) return dlugosc(x-x%10) + dlugosc(x%10);
if(x < 1000) return dlugosc(x-x%100) + dlugosc(x-x%10) + dlugosc(x%10) + 3;
if(x == 1000) return 11;
}
int main()
{
int ile = 0;
for(int i=1; i<=1000; i++)
{
ile += dlugosc(i);
}
cout << ile;
return 0;
}
输入 x=110
不会退出递归。您可以通过 gdb
或手动快速检查:
if(x < 1000) return dlugosc(x-x%100) + dlugosc(x-x%10) + dlugosc(x%10) + 3;
因为 x - x%10
是 x
如果 x
可以被 10
整除,第二项 (dlugosc(x-x%10)
) 将无限递归 x = 110
.