创建一个c#程序,从用户处获取数字作为输入,并将其打印在单词上
本文关键字:输入 单词 打印 数字 一个 创建 用户 程序 获取 | 更新日期: 2023-09-27 18:18:02
无论输入是什么,它都应该以单词为单位打印答案(没有限制),例如输入是2,它应该以单词"TWO"来回答,更多的例子来理解12 =" twelve",51 =" fifty one", 1000 =" one thousand",2005 =" TWO thousand and five"等等…
查看伟大的Humanizer项目。它正好有你所需要的。
3501.ToWords() => "three thousand five hundred and one"
Try this approach:
It's not a complete code, you can improve it by recursive call with
proper range checking etc.
Create a function with input parameter range from 0 to 99 (as shown below):
private string DigitToTextConverter(int digit)
{
string digitText = "";
switch (digit)
{
case 0:
digitText = "zero";
break;
case 1:
digitText = "one ";
break;
case 2:
digitText = "two ";
break;
case 3:
digitText = "three ";
break;
case 4:
digitText = "four ";
break;
case 5:
digitText = "five ";
break;
case 6:
digitText = "six ";
break;
case 7:
digitText = "seven ";
break;
case 8:
digitText = "eight ";
break;
case 9:
.....;
case 10:
.....
case 99:
.....
default:
break;
}
return digitText;
}
//Call this function with appropriate parameter: (suppose user entered 1234)
var userInput = 1234;
var digitText = new StringBuilder();
var quotient = userInput / 1000;
string convertedText = DigitToTextConverter(quotient);
digitText.Append(convertedText + " thousand");
digitText.AppendFormat(" ");
var remainder = userInput % 1000;
quotient = remainder / 100;
convertedText = DigitToTextConverter(quotient);
digitText.Append(convertedText + " thundred");
digitText.AppendFormat(" ");
remainder = remainder % 100;
//Complete remaining portion, better to have a function with recursive call
string finalText = digitText.ToString();