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

C++数字转英文单词:含零数字无法输出Zero的问题修复求助

问题修复:数字转英文单词时无法输出Zero的问题

问题根源

你的代码核心问题在于整数类型无法保留前导零:
当输入900时,第一个while循环试图反转数字,但反转后的结果009会被int自动处理为9,导致后续循环只处理最高位的9,完全丢失了原本的两个0。

修复方案

方案1:直接处理原数字的每一位(无需反转)

通过计算数字的位数,从最高位到最低位依次取出每一位数字并输出对应的英文单词,完整保留所有零:

#include <iostream>
#include <cmath>
using namespace std;

int main(){
    int num; 
    cout << "Enter the number: ";
    cin >> num;

    // 处理输入为0的特殊情况
    if (num == 0) {
        cout << "Zero\n";
        return 0;
    }

    // 计算数字的位数
    int temp = num;
    int digitsCount = 0;
    while (temp != 0) {
        digitsCount++;
        temp /= 10;
    }

    // 从最高位到最低位逐位处理
    for (int i = digitsCount - 1; i >= 0; i--) {
        int divisor = pow(10, i);
        int currentDigit = num / divisor;
        switch (currentDigit) {
            case 0: cout << "Zero\n"; break;
            case 1: cout << "One\n"; break;
            case 2: cout << "Two\n"; break;
            case 3: cout << "Three\n"; break;
            case 4: cout << "Four\n"; break;
            case 5: cout << "Five\n"; break;
            case 6: cout << "Six\n"; break;
            case 7: cout << "Seven\n"; break;
            case 8: cout << "Eight\n"; break;
            case 9: cout << "Nine\n"; break;
        }
        num = num % divisor;
    }

    return 0;
}

方案2:将数字转为字符串处理(更简单直观)

把输入的数字当成字符串直接遍历每个字符,转换为数字后输出对应单词,完全避免整数类型的限制:

#include <iostream>
#include <string>
using namespace std;

int main(){
    string numStr; 
    cout << "Enter the number: ";
    cin >> numStr;

    for (char c : numStr) {
        int digit = c - '0'; // 将字符转为数字
        switch (digit) {
            case 0: cout << "Zero\n"; break;
            case 1: cout << "One\n"; break;
            case 2: cout << "Two\n"; break;
            case 3: cout << "Three\n"; break;
            case 4: cout << "Four\n"; break;
            case 5: cout << "Five\n"; break;
            case 6: cout << "Six\n"; break;
            case 7: cout << "Seven\n"; break;
            case 8: cout << "Eight\n"; break;
            case 9: cout << "Nine\n"; break;
        }
    }

    return 0;
}

测试效果

输入900时,两种方案都会输出:

Nine
Zero
Zero

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:55:25