我是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
答案 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
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 19
,20,30,40...
和100 to 999
添加案例陈述后,它会将1更改为one thousand
,将3更改为three hundred
和80更改为eighty
和4 four
因为它以递归方式调用自身。
另请注意,您不需要84
的个案陈述,只需要80
一个,4
一个,因为您需要分割它了。因此,如果它是85
,则在递归调用时,它将使用相同的80
个案和5
个案。