C#实现0-9999数字转英文单词功能bug排查求助
问题原因分析
- 千位Thousand描述丢失:处理百位数值的逻辑中,直接用
result = first[n] + hundred[0]做赋值操作,直接覆盖了千位逻辑生成的内容,导致千位相关描述被清空。 - 整百/整千末尾多余Zero:最后处理0-19区间的逻辑未做剩余值判断,只要x在0-19区间就拼接对应单词,整百/整千数值经过前面的处理后x会变为0,就会额外拼接
Zero。
修复调整点
- 把百位逻辑的赋值操作从
=改为+=,采用累加方式避免覆盖已生成的千位内容 - 调整0-19区间的拼接规则:仅当剩余x>0,或结果为空(对应输入为0的场景)时才拼接对应单词
- 把超出9999的数值判断提前到逻辑最开始,避免和其他判断分支出现配对错误
- 最后输出时新增Trim操作,去掉末尾多余的空格
修复后完整代码
using System; namespace ITEC102_PT1 { public class Program { public static void Main(string[] args) { string[] first = {"Zero ", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ","Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "}; string[] tens = {"","", "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "}; string hundred = "Hundred "; string thousand = "Thousand "; int n, inputX; string result = ""; Console.WriteLine("•••NUMBER TO WORDS CONVERTER•••"); Console.WriteLine(); Console.Write("Please enter a number in the range of 0-9999 : "); inputX = int.Parse(Console.ReadLine()); Console.WriteLine(); Console.WriteLine(inputX + " in word/s is:"); // 提前校验超出范围的输入 if (inputX >= 10000) { Console.WriteLine("More than 4 numbers is not allowed"); return; } int x = inputX; if (x >= 1000 && x <= 9999) { n = x / 1000; result = first[n] + thousand; x = x % 1000; } if (x >= 100 && x <= 999) { n = x / 100; // 改为累加,不覆盖之前的千位内容 result += first[n] + hundred; x = x % 100; } if (x >= 20 && x <= 99) { n = x / 10; result += tens[n]; x = x % 10; } // 仅剩余值不为0,或是输入为0的场景才拼接最后一位 if (x > 0 || result == "") { result += first[x]; } Console.WriteLine(result.Trim()); } } }
验证效果
- 输入1100,输出为
One Thousand One Hundred,符合预期 - 输入200,输出为
Two Hundred,无多余Zero - 输入1000,输出为
One Thousand,符合预期 - 输入0,输出为
Zero,符合预期
内容的提问来源于stack exchange,提问作者Ray
相关产品推荐
相关产品推荐

