大数的四则运算c++
时间: 2024-06-14 08:07:37 浏览: 105
以下是C++实现大数的四则运算的两个例子:
1. 大数相加
```cpp
bign add(bign a, bign b) {
bign c;
int carry = 0; // 进位
for (int i = 0; i < a.len || i < b.len; i++) {
int 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; // 如果最后一位的进位不为0,直接赋给结果的最高位
}
return c;
}
```
2. 大数乘以一个整数
```cpp
bign multi(bign a, int b) {
bign c;
int carry = 0;
for (int i = 0; i < a.len; i++) {
int temp = a.d[i] * b + carry;
c.d[c.len++] = temp % 10;
carry = temp / 10;
}
while (carry != 0) {
c.d[c.len++] = carry % 10;
carry /= 10;
}
return c;
}
```
阅读全文