无论整型还是长整型,都有它的极限,但有时需要运算很大的数,超过整型的极限。那就需要用字符串保存加数,再进行运算。
在C++学习的环境下,我把写的函数都封装在一个类中,提供一个函数接口供外部使用。
我的思想是:找出两个数较长的,来确定结果字符串的长度,预留一位进位,所以结果字符串的长度会比两个加数的长度大1,最后判断是否去掉首位的字符0。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
//大数加法
class intaddint
{
private:
char *str1;
char *str2;
//封装为私有
void cmp_str();//比较两个加数哪个更长
void int_sum(char *, char *);//计算结果
public:
intaddint(char *, char *);
void get_res();
~intaddint();
};
intaddint::intaddint(char *str1, char *str2)
{
this->str1 = new char[100];//分配内存
this->str2 = new char[100];
memset(this->str1, 0, 100);//清空
memset(this->str2, 0, 100);
strcpy(this->str1, str1);//拷贝要进行运算的数
strcpy(this->str2, str2);
}
void intaddint::cmp_str()
{
int len1 = strlen(str1);
int len2 = strlen(str2);
std::cout << str1 << '+' << str2;
if (len1 >= len2)
int_sum(str1, str2);
else
int_sum(str2, str1);
}
void intaddint::int_sum(char *longstr, char *shortstr)//长加数放在前面
{
int len1 = strlen(longstr);
int len2 = strlen(shortstr);
//转化成数字进行运算
for (int i = 0; i < len1; i++)
longstr[i] -= '0';
for (int i = 0; i < len2; i++)
shortstr[i] -= '0';
char res[100] = { 0 };
int str1_index = len1 - 1;//加数1索引
int str2_index = len2 - 1;//加数2索引
int res_index = len1;//结果的索引,预留一位进位
for (; str2_index >= 0; str2_index--, str1_index--)
{
res[res_index] += longstr[str1_index] + shortstr[str2_index];
if (res[res_index] >= 10)//进位
{
res[res_index - 1] += res[res_index] / 10;//取出进位的值
res[res_index] %= 10;//取模
}
res_index--;
}
if (len1 != len2)//两个加数位数不同需要加上没有进行运算的数
{
while (str1_index >= 0)
{
res[res_index] += longstr[str1_index];
if (res[res_index] >= 10)//进位
{
res[res_index - 1] += res[res_index] / 10;//取出进位的值
res[res_index] %= 10;//取模
}
res_index--;
str1_index--;
}
}
for (res_index = 0; res_index < len1 + 1; res_index++)//再转为字符数字
res[res_index] += '0';
res_index = 0;
while (res[res_index] == '0')//去掉前面的字符'0'
res_index++;
char res_t[100] = { 0 };
int t_index = 0;
for (; res_index < len1 + 1; res_index++, t_index++)//用新的字符串保存结果
res_t[t_index] = res[res_index];
std::cout << '=' << res_t << std::endl;
}
void intaddint::get_res()
{
cmp_str();
}
intaddint::~intaddint()
{
delete[]str1;//清空内存
delete[]str2;
str1 = NULL;//防止野指针
str2 = NULL;
}
void main()
{
char *str1 = "12345678910111213";
char *str2 = "12345678910";
intaddint i(str1, str2);
i.get_res();
system("pause");
}