鱼C论坛

 找回密码
 立即注册
查看: 1467|回复: 2

[已解决]想用c++实现大数加法,但不知道到底出现了什么问题

[复制链接]
发表于 2022-7-18 15:50:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 GaoKui 于 2022-7-18 17:14 编辑

感觉问题出在赋值号上?数据较小时最后两次打印的结果不同,一个是正确的,一个是错误的
数据较大时则是会直接出错,不知道为什么
#include <iostream>
#include <string>

using namespace std;

class BigInt
{
public:
        BigInt(void);
        void getData(void);
        void printData(void);
        BigInt operator+(BigInt &n); // 必须传引用,若传值,参数传入函数后会调用构造函数把原本的数据初始化 
        
private: 
        string data; // 大数 
        int size; // 数字的位数 
};

BigInt::BigInt(void)
{
        data = ""; // 空字符串 
        size = 0;
}

void BigInt::getData(void)
{
        string tmp;
        int i;
        
        getline(cin, tmp); // 先读入数据 
        i = tmp.size(); // i为字符串长度
        
        while (i > 0)
        {
                data[size++] = tmp[--i]; // data中的字符串反着放 
        } 
}

void BigInt::printData(void)
{
        for (int i = size - 1; i >= 0; i--)
        {
                cout << data[i];
        }
        cout << '\n';
}

BigInt BigInt::operator+(BigInt &n)
{
        BigInt result;
        int i, up, tmp; 
        bool flag;
        
        int max = this->size > n.size ? this->size : n.size; // 找到较大的位数
        flag = this->size > n.size ? true : false; // 若是 this指针指向的对象位数大为 true,否则为 false 
        
        if (flag) // 把两个数的位数变一致,位数较小的将前面补上 0
        {
                for (i = n.size; i < max; i++)
                {
                        n.data[i] = '0';
                }
        }
        else
        {
                for (i = this->size; i < max; i++)
                {
                        this->data[i] = '0';
                }
        } 
        
        for (i = 0, up = 0; i < max; i++) // 模拟竖式加法 
        {
                tmp = this->data[i] - '0' + n.data[i] - '0' + up; // 先将两个位对应的和算出,并加上上一位的进位 
                
                result.size++; // 结果长度 +1 
                result.data[i] = tmp % 10 + '0'; // 新的一位是之前的数对 10取余(由于是字符还要加上 '0') 
                up = tmp / 10; // 进位是之前的数除以 10 
        } 
        
        if (up != 0) // 全部结束还有进位,就将进位放到下一位 
        {
                result.size++;
                result.data[i] = up + '0';
        }
        
        // result.printData(); /* ---------------------此处若不注释,打印结果是正确的--------------------- */
        
        return result;
}

int main(void)
{
        BigInt a, b, c; // 创建对象 
        
        a.getData(); // 输入数据 
        b.getData();
        
        c = a + b;
        
        (a + b).printData(); /* ---------------------此处结果正确--------------------- */
        c.printData(); /* ---------------------此处结果错误--------------------- */
        
        return 0;
} 
最佳答案
2022-7-18 20:43:42
问题不在赋值而在对 string 的使用:您对 string 的下标访问是越界的。在容器中,有这样两个大小的概念,分别是容量和大小。其中容量是容器当前最多能够容纳的元素个数,而大小是当前已经实际存储的元素个数。您使用下标访问 data 的方式直接对底层进行了访问,这一步骤是没有越界检查的,而由于默认构造的空(大小为 0 ) string 的容量很可能不为 0 ,因此访问此处的内存是合法的,因而当数据较小时出现诡异的结果,而较大时由于越界而直接报错。
因为直接访问了底层,向 string 添加字符的操作未经过容器的正规接口,容器并不知道自己存储了有效的数据,因此第 99 行赋值时调用 string 的赋值操作符时不会复制这些数据,则在容器的视角看来赋值操作实际进行的是“把一个空字符串复制到 c 中的 data ”,显然这会造成无法从 c 中读出正确的结果。而由于尽管您修改容器内部存储空间的操作对容器不可见,但是您从中读取的操作同样是自行进行的,因此对于 a + b 得到的结果直接读取是能够得到正确结果的。
总结起来,您的问题在于对 string 等标准库容器的理解和使用,可能还需要进一步学习。如果不自信,在初学阶段可以考虑不要使用容器的 [] 运算符而是使用 at 方法,这会引入边界检查从而帮助发现一些问题。另外,个人认为在重载 + 操作符时修改操作数的行为(您的代码中补零的操作)是欠妥的,直观上 + 操作符不应该对两个操作数造成任何(外部可见的)修改。(当然您的实现方式实际上对外部不可见,但是这种实现方式是错误的,因此可能还是需要重新考虑补零这一部分。)
感觉自己没说明白,献丑在您的基础上稍作修改了一下,显然并不是最好的写法,您可以视情况参考。
    #include <iostream>
    #include <string>
    #include <algorithm>

    using namespace std;

    class BigInt
    {
    public:
            BigInt();
            void getData();
            void printData()const;
            BigInt operator+(const BigInt &n)const; // 必须传引用,若传值,参数传入函数后会调用构造函数把原本的数据初始化
           
    private:
            string data; // 大数
            static int addWithCarry(int value, int& carry); // 处理带进位加法,减少代码重复
    };

    BigInt::BigInt() = default;

    void BigInt::getData()
    {
            getline(cin, data);
            reverse(data.begin(), data.end());  // 反转字符串
    }

    void BigInt::printData()const
    {
        for(int i = data.size() - 1; i >= 0; --i) cout << data[i];
        cout << '\n';
    }

    BigInt BigInt::operator+(const BigInt &n)const
    {
            BigInt result;
            int carry = 0;
            unsigned int i = 0;
            while(i < data.size() && i < n.data.size()){
                result.data.push_back(addWithCarry(data[i] - '0' + n.data[i] - '0', carry) + '0');
                ++i;
            }
            while(i < data.size()){
                result.data.push_back(addWithCarry(data[i] - '0', carry) + '0');
                ++i;
            }
            while(i < n.data.size()){
                result.data.push_back(addWithCarry(n.data[i] - '0', carry) + '0');
                ++i;
            }
            if(carry != 0) result.data.push_back('1');
            return result;
    }
    int BigInt::addWithCarry(int value, int& carry){
        carry = (value += carry) >= 10 ? 1 : 0;
        return carry ? value - 10 : value;
    }

    int main()
    {
            BigInt a, b, c; // 创建对象
           
            a.getData(); // 输入数据
            b.getData();
            c = a + b;
           
            (a + b).printData();
            c.printData();
           
            return 0;
    } 
(一开始没想到问题会出在这里,把我给整不自信了,去翻了半天 C++ 标准,还以为记错了默认赋值运算符的行为……)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-7-18 20:43:42 | 显示全部楼层    本楼为最佳答案   
问题不在赋值而在对 string 的使用:您对 string 的下标访问是越界的。在容器中,有这样两个大小的概念,分别是容量和大小。其中容量是容器当前最多能够容纳的元素个数,而大小是当前已经实际存储的元素个数。您使用下标访问 data 的方式直接对底层进行了访问,这一步骤是没有越界检查的,而由于默认构造的空(大小为 0 ) string 的容量很可能不为 0 ,因此访问此处的内存是合法的,因而当数据较小时出现诡异的结果,而较大时由于越界而直接报错。
因为直接访问了底层,向 string 添加字符的操作未经过容器的正规接口,容器并不知道自己存储了有效的数据,因此第 99 行赋值时调用 string 的赋值操作符时不会复制这些数据,则在容器的视角看来赋值操作实际进行的是“把一个空字符串复制到 c 中的 data ”,显然这会造成无法从 c 中读出正确的结果。而由于尽管您修改容器内部存储空间的操作对容器不可见,但是您从中读取的操作同样是自行进行的,因此对于 a + b 得到的结果直接读取是能够得到正确结果的。
总结起来,您的问题在于对 string 等标准库容器的理解和使用,可能还需要进一步学习。如果不自信,在初学阶段可以考虑不要使用容器的 [] 运算符而是使用 at 方法,这会引入边界检查从而帮助发现一些问题。另外,个人认为在重载 + 操作符时修改操作数的行为(您的代码中补零的操作)是欠妥的,直观上 + 操作符不应该对两个操作数造成任何(外部可见的)修改。(当然您的实现方式实际上对外部不可见,但是这种实现方式是错误的,因此可能还是需要重新考虑补零这一部分。)
感觉自己没说明白,献丑在您的基础上稍作修改了一下,显然并不是最好的写法,您可以视情况参考。
    #include <iostream>
    #include <string>
    #include <algorithm>

    using namespace std;

    class BigInt
    {
    public:
            BigInt();
            void getData();
            void printData()const;
            BigInt operator+(const BigInt &n)const; // 必须传引用,若传值,参数传入函数后会调用构造函数把原本的数据初始化
           
    private:
            string data; // 大数
            static int addWithCarry(int value, int& carry); // 处理带进位加法,减少代码重复
    };

    BigInt::BigInt() = default;

    void BigInt::getData()
    {
            getline(cin, data);
            reverse(data.begin(), data.end());  // 反转字符串
    }

    void BigInt::printData()const
    {
        for(int i = data.size() - 1; i >= 0; --i) cout << data[i];
        cout << '\n';
    }

    BigInt BigInt::operator+(const BigInt &n)const
    {
            BigInt result;
            int carry = 0;
            unsigned int i = 0;
            while(i < data.size() && i < n.data.size()){
                result.data.push_back(addWithCarry(data[i] - '0' + n.data[i] - '0', carry) + '0');
                ++i;
            }
            while(i < data.size()){
                result.data.push_back(addWithCarry(data[i] - '0', carry) + '0');
                ++i;
            }
            while(i < n.data.size()){
                result.data.push_back(addWithCarry(n.data[i] - '0', carry) + '0');
                ++i;
            }
            if(carry != 0) result.data.push_back('1');
            return result;
    }
    int BigInt::addWithCarry(int value, int& carry){
        carry = (value += carry) >= 10 ? 1 : 0;
        return carry ? value - 10 : value;
    }

    int main()
    {
            BigInt a, b, c; // 创建对象
           
            a.getData(); // 输入数据
            b.getData();
            c = a + b;
           
            (a + b).printData();
            c.printData();
           
            return 0;
    } 
(一开始没想到问题会出在这里,把我给整不自信了,去翻了半天 C++ 标准,还以为记错了默认赋值运算符的行为……)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-7-18 23:18:03 | 显示全部楼层
dolly_yos2 发表于 2022-7-18 20:43
问题不在赋值而在对 string 的使用:您对 string 的下标访问是越界的。在容器中,有这样两个大小的概念,分 ...

十分感谢!虽然有一小部分还是没看懂,应该是还没完全掌握相关的知识。会继续学习的!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-6 08:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表