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

大整数加法实现遇字符转整数问题,求C++代码调试帮助

大整数加法代码问题求助

正在完成CodeUp平台编号3021的大整数加法题目,要求实现超100位的大整数加法(32位int和64位long long无法存储这类大数)。用6天前学的stack写了C++代码,但执行c.push((int)a[o] - '0')字符转整数的步骤后代码无法正确运行,尝试过-'0'的转换方式还是不行,希望得到帮助。

我的代码:

#include <stdio.h>
#include <stack>
#include <vector>
using namespace std;
stack<int> c,d;//stack for adding large numbers
int main(){
    char a[100]={'0'};
    char b[100]={'0'};//input variables
    int i=0,j=0,m;
    scanf("%s %s", a, b);
    while (a[i] != '\0') {
        i++;
    }

    i--;
    while (b[j] != '\0') {
        j++;
    }
    j--;
    if (i>j) {
        m=i;
    } else {
        m=j;
    }
    for (int o=0;o<=m;o++) {
         c.push((int)a[o] - '0');//main problem is converting char to int.
    }

    for (int o=0;o<=m;o++) {
         d.push((int)b[o] - '0');
    }

    int carry=0;//carry variable

    for (int o=0;o<=m;o++) {
        if (c.top()+d.top()+carry>=10) {
            printf("%d", c.top() + d.top() + carry - 10);
            carry=1;
        } else {
            printf("%d", c.top() + d.top() + carry);
            carry=0;
        }
        c.pop();
        d.pop();
    }
    if (carry > 0) {
        printf("%d", carry);
    }
    return 0;
}

问题分析与修正

你代码里的字符转整数逻辑(int)a[o] - '0'本身是对的,问题出在其他逻辑上:

  • 入栈顺序错误:大整数加法需要从个位开始计算,你现在从字符串首字符(最高位)入栈,导致栈顶是最高位,计算顺序完全相反。应该从字符串末尾(个位)开始遍历入栈。
  • 越界访问风险:当两个数字长度不同时,短字符串超出自身长度的位置不一定是'0',会转换出无效数值。应该在遍历判断是否超出字符串长度,超出则补0。
  • 输出顺序错误:直接打印每一步结果会得到反向的数字,需要把结果存入栈中,最后弹出输出才能保证顺序正确。

修正后的代码:

#include <stdio.h>
#include <stack>
using namespace std;

int main(){
    char a[101] = {0}; // 多留一位存储字符串结束符
    char b[101] = {0};
    stack<int> numA, numB, result;
    int carry = 0;

    scanf("%s %s", a, b);

    // 从个位开始将数字压入栈
    int i = 0;
    while (a[i] != '\0') i++;
    for (int k = i - 1; k >= 0; k--) {
        numA.push(a[k] - '0');
    }

    int j = 0;
    while (b[j] != '\0') j++;
    for (int k = j - 1; k >= 0; k--) {
        numB.push(b[k] - '0');
    }

    // 逐位相加,处理进位
    while (!numA.empty() || !numB.empty() || carry != 0) {
        int sum = carry;
        if (!numA.empty()) {
            sum += numA.top();
            numA.pop();
        }
        if (!numB.empty()) {
            sum += numB.top();
            numB.pop();
        }
        carry = sum / 10;
        result.push(sum % 10);
    }

    // 输出最终结果
    while (!result.empty()) {
        printf("%d", result.top());
        result.pop();
    }
    printf("\n");

    return 0;
}

修正点说明

  1. 入栈顺序调整:从字符串末尾(个位)遍历压栈,确保栈顶是最低位,符合加法从低位到高位的计算顺序。
  2. 兼容不同长度:通过判断栈是否为空来处理不同长度的数字,空栈则不再取值,自动补0;同时保留进位判断,确保最后一位的进位能被处理。
  3. 结果存储与输出:将每一步计算结果压入结果栈,最后依次弹出打印,保证输出顺序是从高位到低位的正确数值。

内容的提问来源于stack exchange,提问作者해공부

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 08:33:14