一次以英文形式逐个打印整数 [英] Printing an integer each digit at a time in english form recursively

查看:148
本文介绍了一次以英文形式逐个打印整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经给了一个赋值,我们必须使用递归方法以英文形式逐个打印出整数。例如。 534打印出五三四。

I've been given an assignment where we must print out an integer digit by digit in english form using a recursive method. E.G. 534 prints out "five three four".

这是我的:

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);
}

由于某种原因,它打印出英文中最低的数字到最高的数字。 。

For some reason it's printing out the lowest digit to the highest digit in English...Shouldn't this keep returning until it reaches the first digit then print it out, and then print out each digit up as the stack unwinds?

推荐答案

发生这种情况是因为您的方法在您递归下来的调用中不做任何操作。您应该在每次调用中执行打印,但只有在 num 不为零时才会递归。

This happens because your method does not do anything in the invocations where you recurse down. You should do a print in each invocation, but recurse down only when the num is not zero.

(伪代码)应该如下:

The algorithm (in pseudocode) should be as follows:

englishInt(int num) {
    if (num != 0) {
        englishInt(num/10)
    }
    cout << english letter for (num % 10)
}

c $ c> num == 0 ,因此调用 englishInt(0)会产生一些输出。

You need a special case for num == 0, so that calling englishInt(0) would produce some output.

这篇关于一次以英文形式逐个打印整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆