【例1.2】高精度减法

       输入两个正整数,求它们的差
【算法分析】
       类似加法,可以用竖式求减法。在做减法运算时,需要注意的是,被减数必须比减数大,同时需要处理借位。
【参考程序】

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

int main() {
	int a[256], b[256], c[256], lena, lenb, lenc;
	char t[256], a1[256], b1[256];
	
	memset(a, 0, sizeof(a));
	memset(b, 0, sizeof(b));
	memset(c, 0, sizeof(c));
	
	printf("Input minuend:");		
	gets(a1);							// 输入被减数 
	printf("Input subtrahend:");
	gets(b1);							// 输入减数
	if ((strlen(a1)<strlen(b1)) || ((strlen(a1)==strlen(b1)) && (strcmp(a1,b1)<0))) {
		strcpy(t, a1);					// 交换字符串a1和b1		 
		strcpy(a1, b1);
		strcpy(b1, t);
		cout <<"-";						// 交换了减数和被减数,结果为负数 
	} 
	lena = strlen(a1);
	lenb = strlen(b1);
	
	for (int i=0; i<lena; i++) { 
		a[lena-i] = a1[i] - 48;			// 被减数放入数组a 
	}
	for (int i=0; i<lenb; i++) {
		b[lenb-i] = b1[i] - 48;			// 减数放入数组b 
	}
	
	lenc = 1;
	while (lenc <= lena) {
		if (a[lenc] < b[lenc]) {
			a[lenc] += 10;				// 不够减,向高位借1当10
			a[lenc+1]--; 
		}
		c[lenc] = a[lenc] - b[lenc];	// 对应为相减
		lenc++; 
	}
	
	while ((c[lenc]==0) && (lenc>1)) {	// 最高位的0不输出 
		lenc--;
	}
	for (int i=lenc; i>=1; i--) {
		cout << c[i];
	} 
	
	return 0;
}

发布了49 篇原创文章 · 获赞 0 · 访问量 1035

猜你喜欢

转载自blog.csdn.net/developer_zhb/article/details/105003977