如何将此整数值转换为此程序中的字符串? (详细信息)

时间:2016-03-24 09:49:38

标签: c#

我从Stackoverflow上的另一个页面找到的这段代码将数字转换为正确命名的口头对应词。代码工作正常,但我不能解决为什么,例如,如果我输入1000000(100万)

if ((number / 1000000) > 0)
{
    words += NumberToWords(number / 1000000) + " Million ";
    number %= 1000000;   
}

这是困扰我的部分,它分配字符串单词[NumberToWords(number/1000000) + " Million "。我得到百万分之一部分,但程序如何计算出字符串的第一部分确实是" One"

以下是完整代码:

Console.WriteLine("Please enter a number to convert [Between 1 and 1 million]:");

int intUser = Int32.Parse(Console.ReadLine());
Console.WriteLine("{0}", NumberToWords(intUser));
Console.ReadKey();

public static string NumberToWords(int number)
{
    if (number == 0)
       return "Zero";

    if (number < 0)
       return "Minus " + NumberToWords(Math.Abs(number));

    string words = "";

    if ((number / 1000000) > 0)
    {
        words += NumberToWords(number / 1000000) + " Million ";
        number %= 1000000;
    }

    if ((number / 1000) > 0)
    {
        words += NumberToWords(number / 1000) + " Thousand ";
        number %= 1000;
    }

    if ((number / 100) > 0)
    {
        words += NumberToWords(number / 100) + " Hundred ";
        number %= 100;
    }

    if (number > 0)
    {
        if (words != "")
            words += "and ";

        var unitsMap = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
        var tensMap = new[] { "Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };

        if (number < 20)
            words += unitsMap[number];
        else
        {
            words += tensMap[number / 10];

            if ((number % 10) > 0)
                words += "-" + unitsMap[number % 10];
        }
    }

    return words;
}

1 个答案:

答案 0 :(得分:1)

它是一个递归函数,为字符串中的每个数字调用自身。单个数字用作从数组中检索字符串值的索引。

var unitsMap = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };

示例 - unitMap[5]会产生'五'