如何获得不同的数字,从最显著位在c进行编号开始? [英] how to get different digits starting from the most significant digit in a number in c?

查看:104
本文介绍了如何获得不同的数字,从最显著位在c进行编号开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我解决这一个正整数,给出一个问题,我有话要显示它。

I am solving a problem in which a positive integer is given and i have to display it in words.

例如,如果一个号码是 2134 输出应为二一三四
如果我使用模运算符和使用递归方法,我得到的数字从最低显著位即启动四三一二

For example if a number is 2134 the output should be "two one three four" . If i use the modulus operator and use the recursion technique, i get the digits starting from the least significant digit i.e "four three one two"

我也能逆转号码,然后使用模运算,但我想找一个更好的方法。

I can also reverse the number and then use modulus operator but i am looking for a better method.

有什么可以解决这个问题的一个更好的方法?。什么概念,我缺少什么?

What can be a better approach of solving this problem?.What concept am i missing?

推荐答案

我的答案很简单:

void printNum(int x)
{
    static const char * const num[] = {
        "zero ", "one ", "two "  , "three ", "four ",
        "five ", "six ", "seven ", "eight ", "nine "
    };

    if (x < 10) {
        printf(num[x]);
        return;
    }
    printNum(x / 10);
    printNum(x % 10);
}

修改

经过一些试验和调整,我想出了这个版本。
我想,这大概是最纯粹的递归函数,我可以做。

After some more experimenting and tweaking, I came up with this version. I think this is the about the most "pure" recursive function I can make.

void printNum(int x)
{
    static const char * const num[] = {"zero ",  "one ", "two ", "three ",
                                       "four ",  "five ", "six ", "seven ",
                                       "eight ", "nine "};
    (x < 10)? printf(num[x]) : (printNum(x / 10), printNum(x % 10));
}

这篇关于如何获得不同的数字,从最显著位在c进行编号开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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