在vb.net中仅使用SELECT CASE将数字转换为单词

时间:2017-08-07 15:46:50

标签: vb.net

我是vb.net环境中的新手。因此,我们的教授要求我们仅使用Select Case将数字转换为单词。我们只允许使用SELECT CASE - If,If if else,不允许使用数组等。问题是我在一个"硬代码"方式,我希望它更多"清洁"高效和最大数量最多为5位数。我希望有人可以就此提出好主意。

    Dim one As String = "One"
    Dim two As String = "Two"
    Dim three As String = "Three"
    Dim four As String = "Four"
    Dim five As String = "Five"
    Dim six As String = "Six"
    Dim seven As String = "Seven"
    Dim eight As String = "Eight"
    Dim nine As String = "Nine"
    Dim ten As String = "Ten "
    Dim twenty As String = "Twenty "
    Select Case input >= 20 And input <= 99
        Case True
            Select Case input
                Case 20
                    lblOutput.Text = twenty
                Case 21
                    lblOutput.Text = twenty + one
                Case 22
                    lblOutput.Text = twenty + two
                Case 23
                    lblOutput.Text = twenty + three

1 个答案:

答案 0 :(得分:1)

可以使用30个案例语句和29个文字字符串来完成。这不是完整的解决方案,您需要添加更多逻辑。

这些是表示1到99,999之间数字所需的不同词语:

one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty
thirty
fourty
fifty
sixty
seventy
eighty
ninety
hundred
thousand
输入为1到19时需要

one to nineteen

当输入为20到99

时,需要

twenty to ninety 当输入为100到999

时,需要

hundred 输入&gt; = 1000

时需要

thousand

因此,例如,如果数字是1384,则将其分解为多个部分并递归调用相同的函数以返回单词。

    Private Function convertToWords(input As Integer) As String
        Dim words As String = ""

        Select Case input
            Case 1
                words = "one"

            Case Is >= 1000
                Dim thousands As Integer = (input \ 1000) '<= how many 1000's are there?
                Select Case thousands
                    Case Is > 0
                        input = (input Mod 1000) '<= the remainder is the new value which will be used by calling the same function again
                        words &= convertToWords(thousands) & " thousand " & convertToWords(input)
                End Select    
        End Select

        Return words
    End Function

有1千,其余为384,它们成为新的输入,它将被传递到同一个函数中,然后以相同的方式分成数百个。

1 to 1920,30,40...100 to 999添加案例陈述后,它会将1更改为one thousand,将3更改为three hundred和80更改为eighty和4 four因为它以递归方式调用自身。

另请注意,您不需要84的个案陈述,只需要80一个,4一个,因为您需要分割它了。因此,如果它是85,则在递归调用时,它将使用相同的80个案和5个案。