面试技能五

最后更新于:2022-04-01 21:06:35

用C#写一个CheckWriter的控制台程序,如果你在银行工作,需要一个系统能够当你输入一串数字金额后能用其对应的英文输出,这样方便打印在支票上防止篡改。用户输入一个0到20亿的数字包含最多2位小数,将其转换为英文输出。例如输入1258276.25,能够输出:one million, three hundred and fifty seven thousand, two hundred and fitty six DOLLARS AND thirty two CENTS. ~~~ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CheckWriter { class Program { private static string[] _lessTwentyNumbers = new string[]{"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen","Sixteen", "Seventeen", "Eighteen", "Nineteen"}; private static string[] _lessHundredNumbers = new string[]{"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty","Ninety"}; private static string[] _scaleNumbers = new string[] { "", "Thousand", "Million", "Billion" }; static void Main(string[] args) { string s = ConvertDecimalToWords(1258276.25); Console.WriteLine(s); Console.Read(); } /// /// 将数字转为英文描述 /// /// /// private static string ConvertNumberToWords(int number) { if (number == 0) { return _lessTwentyNumbers[0]; } int[] digitGroups = new int[4]; int positive = Math.Abs(number); // 将数字按三位一段保存到数组里 for (int i = 0; i < 4; i++) { digitGroups[i] = positive % 1000; positive /= 1000; } string[] groupText = new string[4]; for (int i = 0; i < 4; i++) { // 每三位一段转为相应的英文字符 groupText[i] = ConvertThreeDigitToWords(digitGroups[i]); } string combined = groupText[0]; for (int i = 1; i < 4; i++) { if (digitGroups[i] != 0) { // 每一段加上相应的这一段的级别数字 string prefix = groupText[i] + " " + _scaleNumbers[i]; if (!string.IsNullOrEmpty(prefix)) { if (string.IsNullOrEmpty(combined)) { combined = prefix; } else { combined = prefix + ", " + combined; } } } } if (number < 0) { combined = "Negative " + combined; } return combined; }  /// /// 处理三位数以内的数字转为英文描述 /// /// /// private static string ConvertThreeDigitToWords(int threeDigits) { string groupText = ""; // 获取百位 int hundreds = threeDigits / 100; int tensUnits = threeDigits % 100; if (hundreds != 0) { groupText += _lessTwentyNumbers[hundreds] + " Hundred"; if (tensUnits != 0) { groupText += " and "; } } // 获取十位 int tens = tensUnits / 10; int units = tensUnits % 10; if (tens >= 2) { groupText += _lessHundredNumbers[tens]; if (units != 0) { groupText += " " + _lessTwentyNumbers[units]; } } else if (tensUnits != 0) { groupText += _lessTwentyNumbers[tensUnits]; } return groupText; } private static string ConvertDecimalToWords(double number) { int i = (int)number; int p = (int)((number - i) * 100); return ConvertNumberToWords(i) + " DOLLARS AND " + ConvertNumberToWords(p) + " CENTS"; } } } ~~~ 上面的代码中两个核心函数是ConvertNumberToWords和ConvertThreeDigitToWords,ConvertThreeDigitToWords的作用主要是能将小于1000的整数转为相应的金额,而ConvertNumberToWords负责将不同段的金额组合成完整的金额,主要是加上了该金额对应的位,例如本程序由于只要求对20亿以内的数字进行处理,因此分为千,百万和十亿三档。理解好了这两个函数基本就能知道是怎么做的。
';