#include<iostream>//定义结构体,从string中保存大数到数组中,其中整数位4位一逆序保存到dig1;小数位1位一顺序保存到dig2(因为小数位计算加法0.1+0.12=0.22,如果和整数位一样保存
#include<string>//和计算会出问题,比如会算成0.1+0.12=0.13;
#include<iomanip>
using namespace std;
struct M
{
int dig1[1000];
int dig2[4000];
int size1;
int size2;
void init()
{
for (int i = 0; i < 1000; i++)
{
dig1[i] = dig2[i] = 0;
size1 = size2 = 0;
}
}
void set(string x)
{
init();
int n = x.length();
int len = x.find('.', 0);//偷懒用了string类的find函数找到'.'的下标,
string y(x, len + 1, n);//然后从小数位开始到x的末位全部拷贝到新的y中
int len1 = y.length();
int i, j;
int c = 1, temp = 0;
for (i =0, j = 0; i<len1; i++)//直接从y[0]开始逐位保存到dig2[]中去
{
dig2[i] = y[i] - '0';
size2++;
}
for (int i= len-1, j = 0; i >= 0; i--)
{
temp += (x[i] - '0') * c;
c *= 10;
j++;
if (j == 4 || i == 0)
{
dig1[size1++] = temp;
temp = 0; j = 0; c = 1;
}
}
}
void output()
{
for (int i = size1 - 1; i >= 0; i--)
{
if (i != size1 - 1)
cout << setw(4) << setfill('0') << dig1[i];
else
cout << dig1[i];
}
cout << ".";
for (int i = size2 - 1; i >= 0; i--)
{
cout << dig2[i];
}
cout << endl;
}
M operator+(M& s)//重载+
{
M ret;
ret.init();
int carry = 0, temp = 0;
//nt len = size2 - s.size2;
//f (len < 0)
if (size2 > s.size2)//将两个保存小数的数组变成等长的数组如123和1234,将123变成1230,便于计算,因为一开始全部初始化了,所以size外的全部填为0了,所以不需要重新赋值
s.size2 = size2;
else
size2 = s.size2;
for(int i =size2-1; i>=0 ; i--)
{
temp = dig2[i] + s.dig2[i] + carry;//逢10进1
carry = temp / 10;
temp %= 10;
ret.dig2[ret.size2++] = temp;
}
temp = 0;
for (int i = 0; i < size1 || i < s.size1; i++)
{
temp = dig1[i] + s.dig1[i] + carry;//逢10000进
carry = temp / 10000;
temp %= 10000;
ret.dig1[ret.size1++] = temp;
}
if (carry != 0)
ret.dig1[ret.size1++] = carry;
return ret;
}
}p,q,r;
string x1, x2;
int main()
{
while (cin >> x1>>x2)
{
p.set(x1);
q.set(x2);
r = p + q;
r.output();
}
}
还有一种方法,字符串前补0和后补0的方法,位数不同的可以用0补齐位数
前补0
str='0'+str;
后补0
str=str+'0';