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

数字反转程序输出不符预期,输入10无法得到01如何解决?

数字反转前导零丢失问题的解决方案

问题根源分析

你的代码存在两个核心问题:

  1. 变量未初始化:int n;没有赋初始值,直接执行n = n*10 + r会触发未定义行为,运行结果可能随机。
  2. 整数类型特性限制:整数本身不会存储前导零,即使反转逻辑正确,输出时前导零也会被自动忽略——比如输入10反转后得到的整数是1,输出自然只会显示1。

解决方案一:字符串反转(推荐)

直接将输入当作字符串处理,反转字符串即可保留前导零,实现最简单直观:

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

class sample{
public:
    void rev();
};

void sample::rev(){
    cout << "Enter a no: ";
    string num;
    cin >> num;
    reverse(num.begin(), num.end());
    cout << num << endl;
}

int main(){
    sample A;
    A.rev();
    return 0;
}

输入10时,程序会直接输出01,完全符合你的预期。

解决方案二:整数反转+补零(适合需数值运算的场景)

如果必须基于整数反转逻辑,需要先记录原数字的位数,反转后根据位数补全前导零:

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

class sample{
public:
    void rev();
};

void sample::rev(){
    cout << "Enter a no: ";
    int x;
    cin >> x;
    int original = x;
    int digitCount = 0;

    // 统计原数字的位数
    if(x == 0){
        digitCount = 1;
    } else {
        while(original != 0){
            digitCount++;
            original /= 10;
        }
    }

    int n = 0; // 必须初始化n
    int temp = x;
    while(temp != 0){
        int r = temp % 10;
        n = n * 10 + r;
        temp /= 10;
    }

    // 计算需要补的前导零数量
    int zerosNeeded = digitCount - (n == 0 ? 1 : (int)log10(n) + 1);
    // 输出前导零
    for(int i=0; i<zerosNeeded; i++){
        cout << "0";
    }
    cout << n << endl;
}

int main(){
    sample A;
    A.rev();
    return 0;
}

这个方案先统计原数字的位数,反转后计算缺失的零的个数,输出时补全,同样能得到01的结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:40:26