You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++数字转英文程序问题排查:101-109输出异常且崩溃,遗漏110-119分支

解决C++数字转英文的崩溃与逻辑遗漏问题

咱们先逐个拆解你的问题:

一、101~109乱码崩溃的核心原因

大概率是数组越界访问未初始化内存,或者处理十位为0的逻辑有误:

  • 假设你定义了tens数组存储十位的英文(比如"Twenty", "Thirty"...),如果数组索引从1开始对应十位的1(但十位为0时没有对应项),当处理101这类十位为0的数字时,程序错误地去访问tens[0],就会读取到内存里的随机垃圾数据(也就是你看到的乱码),甚至直接触发内存访问错误导致崩溃。
  • 另一种可能是,你没判断十位为0的情况,强行拼接了十位对应的空/无效字符串,导致内存操作异常。

二、110~119的逻辑遗漏解决办法

这类数字是“百位+1119”的组合,不能拆成“百位+十位+个位”处理,必须单独判断百位后的余数是否在1119区间,直接使用专门的teens数组(存储"Eleven"到"Nineteen")。

修复后的核心逻辑示例

给你一段关键代码参考,对应三位数的处理逻辑:

#include <string>
using namespace std;

const string ones[] = {"", "One", "Two", "Three", "Four", "Five", 
                       "Six", "Seven", "Eight", "Nine"};
const string teens[] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", 
                        "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
const string tens[] = {"", "", "Twenty", "Thirty", "Forty", "Fifty", 
                       "Sixty", "Seventy", "Eighty", "Ninety"};

string numberToWords(int num) {
    if (num < 1 || num > 999) return "Invalid number";
    
    string result;
    // 处理百位
    if (num >= 100) {
        result += ones[num / 100] + " hundred";
        int remainder = num % 100;
        if (remainder != 0) {
            result += " and ";
            // 判断余数是否是11~19(覆盖110~119的情况)
            if (remainder >= 11 && remainder <= 19) {
                result += teens[remainder - 10];
            } else {
                int ten = remainder / 10;
                int one = remainder % 10;
                // 处理十位为0的情况(对应101~109)
                if (ten != 0) {
                    result += tens[ten];
                    if (one != 0) result += " " + ones[one];
                } else {
                    result += ones[one];
                }
            }
        }
        return result;
    }
    // 处理两位数和一位数的逻辑
    if (num >= 11 && num <= 19) {
        return teens[num - 10];
    } else {
        int ten = num / 10;
        int one = num % 10;
        string res = tens[ten];
        if (one != 0) res += " " + ones[one];
        return res;
    }
}

额外排查点

  • 检查你定义的字符串数组是否初始化完整,比如ones数组的索引0是不是空字符串(用来占位,避免越界)。
  • 测试时单步调试101的处理流程,看程序是不是走到了正确的分支(十位为0时直接输出个位,而不是去访问tens数组的无效索引)。

内容的提问来源于stack exchange,提问作者Luke Michaels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:30:15