我已经获得了一项任务,我们必须使用递归方法以英文形式逐位打印整数。例如。 534打印出“五三四”。
这就是我所拥有的:
int englishInt(int num) {
if(num < 10) {
switch(num) {
case 0: cout << "zero ";
case 1: cout << "one ";
case 2: cout << "two ";
case 3: cout << "three ";
case 4: cout << "four ";
case 5: cout << "five ";
case 6: cout << "six ";
case 7: cout << "seven ";
case 8: cout << "eight ";
case 9: cout << "nine ";
}
} else
return englishInt(num / 10);
}
出于某种原因,它打印出最低位数到英文的最高位数...这不应该一直保持返回,直到它到达第一个数字然后将其打印出来,然后在堆栈展开时打印出每个数字?
答案 0 :(得分:4)
用一个例子来思考,比如537。
englishInt(537) -- prints nothing, calls
englishInt(53) -- prints nothing, calls
englishInt(5) -- prints "five six seven eight nine"
原因是:
break
陈述。num >= 10
。答案 1 :(得分:2)
这是因为您的方法在您递归的调用中没有做任何事情。您应该在每次调用时执行打印,但仅在num
不为零时才递减。
算法(伪代码)应如下:
englishInt(int num) {
if (num != 0) {
englishInt(num/10)
}
cout << english letter for (num % 10)
}
num == 0
需要一个特殊情况,因此调用englishInt(0)
会产生一些输出。
答案 2 :(得分:1)
首先,我看到修改代码的最小变化。
break
。因此,
void englishInt(int num)
{
if (num >=10)
englishInt(num/10);
switch(num % 10)
{
case 0: cout << "zero "; break;
case 1: cout << "one "; break;
case 2: cout << "two "; break;
case 3: cout << "three "; break;
case 4: cout << "four "; break;
case 5: cout << "five "; break;
case 6: cout << "six "; break;
case 7: cout << "seven "; break;
case 8: cout << "eight "; break;
case 9: cout << "nine "; break;
}
}
疏忽开关
我不是在关注为什么你首先有一个switch语句。如果你看看你的开关,你总是在评估0..9
之间的数字。那么为什么不将这个数字用于一个包含十个字符串数组的简单索引:
#include <iostream>
using namespace std;
void print_num(unsigned int num)
{
static const char *strs[] =
{
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"
};
if (num >= 10)
print_num(num/10);
cout << strs[num % 10] << ' ';
}
int main(int argc, char *argv[])
{
print_num(100); cout << endl;
print_num(12345); cout << endl;
print_num(3); cout << endl;
print_num(1024*1024*1024); cout << endl;
return 0;
}
<强>输出强>
one zero zero
one two three four five
three
one zero seven three seven four one eight two four
答案 3 :(得分:0)
您的代码存在一些问题。
首先,你的switch语句被破坏了:你忘了在每个案例之后放一个break
语句,所以在递归结束时你的程序会打印出最重要的数字,然后遍历更大的数字到9。
修复如下:
switch(num) {
case 0: cout << "zero "; break;
case 1: cout << "one "; break;
case 2: cout << "two "; break;
case 3: cout << "three "; break;
case 4: cout << "four "; break;
case 5: cout << "five "; break;
case 6: cout << "six "; break;
case 7: cout << "seven "; break;
case 8: cout << "eight "; break;
case 9: cout << "nine "; break;
}
其次,您的程序将只有最高位数的输出。您不打印中间步骤的任何内容。这不是你的代码的问题,而是你的算法,所以你必须自己修复它。
答案 4 :(得分:-1)
要做的狂野方法
int main()
{
int n;
char s[32];
char word[10][10]{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
cout << "enter a number" << endl;
cin >> n;
sprintf(s,"%d", n );
for( int i = 0; s[i] != '\0'; i++)
{
cout << word[s[i]-'0'];
}
return 0;
}