大整数运算
#include <iostream>
#include <cstring>
using namespace std;
struct bign
{
int d[1000];
int len;
bign()
{
memset(d, 0, sizeof(d));
len = 0;
}
};
bign change(char str[])
{
bign a;
a.len = strlen(str);
for (int i = 0; i < a.len; i++)
{
a.d[i] = str[a.len - 1 - i]-'0';
}
return a;
}
void print(bign a)
{
for (int i = a.len - 1; i >= 0; i--)
{
printf("%d", a.d[i]);
}
}
bign add(bign a, bign b)
{
bign c;
int temp,carry=0;
for (int i = 0;i < a.len || i < b.len; i++)
{
temp = a.d[i] + b.d[i] + carry;
c.d[c.len++] = temp % 10;
carry = temp / 10;
}
if (carry != 0)
{
c.d[c.len++] = carry;
}
return c;
}
bign sub(bign a, bign b)
{
bign c;
for (int i = 0; i < a.len || i < b.len; i++)
{
if (a.d[i] < b.d[i])
{
a.d[i + 1]--;
a.d[i] += 10;
}
c.d[c.len++] = a.d[i] - b.d[i];
}
while (c.len - 1 >= 1 && c.d[c.len - 1] == 0)
{
c.len--;
}
return c;
}
bign divide(bign a, int b, int& r)
{
bign c;
c.len = a.len;
for (int i = a.len - 1; i >= 0; i--)
{
r = r * 10 + a.d[i];
if (r < b) c.d[i] = 0;
else
{
c.d[i] = r / b;
r = r % b;
}
}
while (c.len - 1 >= 1 && c.d[c.len - 1] == 0)
{
c.len--;
}
return c;
}
bign mul(bign a, int b)
{
bign c;
int carry = 0;
for (int i = 0; i < a.len; i++)
{
carry += a.d[i] * b;
c.d[c.len++] = carry % 10;
carry /= 10;
}
while (carry != 0)
{
c.d[c.len++] = carry % 10;
carry /= 10;
}
return c;
}
int main()
{
printf("加法请输入1\n");
printf("减法请输入2\n");
printf("乘法请输入3\n");
printf("除法请输入4\n");
printf("请输入您的选择:");
int choose,b;
cin >> choose;
char str1[1000], str2[1000];
if (choose == 1)
{
printf("请输入两个数字以空格作为分隔符\n");
char str1[1000], str2[1000];
cin >> str1 >> str2;
print(add(change(str1), change(str2)));
}
else if (choose == 2)
{
printf("请输入两个数字以空格作为分隔符\n");
cin >> str1 >> str2;
print(sub(change(str1), change(str2)));
}
else if (choose == 4)
{
printf("请输入两个数字以空格作为分隔符\n");
int r=0;
cin >> str1 >> b;
print(divide(change(str1), b,r));
}
else if (choose == 3)
{
printf("请输入两个数字以空格作为分隔符\n");
cin >> str1 >> b;
print(mul(change(str1), b));
}
else
{
printf("没有你需要的运算\n");
}
return 0;
}