我今天让我的学生写了这段代码,但它出现了错误,我不太明白为什么。英语数字发音的问题是数字母。它是最早的欧拉投影问题之一。递归有问题吗?
#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
无限递归。