无符号大数加、减运算。程序设计中经常遇到无符号大数加、减运算问题,请在样例程序Ex1.4基础上实现无符号大数减运算。题目要求输入两个无符号大数,保证一个大数不小于第二个大数,输出它们的和、差。
时间: 2024-03-20 18:43:42 浏览: 55
好的,我已经明白了您的问题。以下是一份使用 C++ 实现的无符号大数减法的示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 1005; // 定义最大位数
int a[MAXN], b[MAXN], c[MAXN]; // 分别存放被减数、减数、差
int lena, lenb, lenc; // 分别记录三个数的长度
// 大数减法
void substract() {
int borrow = 0; // 借位
for (int i = 0; i < lenc; i++) {
int temp = a[i] - b[i] - borrow; // 当前位的运算结果
if (temp < 0) { // 需要借位
temp += 10;
borrow = 1;
} else {
borrow = 0;
}
c[i] = temp;
}
// 去除前导0
while (lenc > 1 && c[lenc - 1] == 0) {
lenc--;
}
}
int main() {
string str1, str2;
cin >> str1 >> str2; // 输入两个大整数
lena = str1.length();
lenb = str2.length();
// 将字符串转换为数组
for (int i = 0; i < lena; i++) {
a[i] = str1[lena - i - 1] - '0';
}
for (int i = 0; i < lenb; i++) {
b[i] = str2[lenb - i - 1] - '0';
}
lenc = max(lena, lenb); // 差的最大长度不超过两个数中的最大值
substract(); // 计算两个数的差
// 输出结果
for (int i = lenc - 1; i >= 0; i--) {
cout << c[i];
}
cout << endl;
return 0;
}
```
在这份代码中,我们定义了三个数组分别存放被减数、减数和差。由于输入的是字符串,因此我们需要将字符串转换为数组。在大数减法的实现中,我们需要用到借位的概念,即当前位不够减,需要从高位借位。最后,我们需要去除计算结果中的前导0,输出时也需要逆序输出。