模板 C/C++高精度加法

高精度加法

实现步骤

  1. 输入两个字符串并计算其字符串长度。
  2. 若两个字符串长度不等,在较短字符串前补’0’,使两个字符串长度相等。
  3. 将字符串存到整型数组中,记得要逆序存储,并且从下标值1开始存储。
  4. 通过一个循环将两个整型数组相加。
  5. 判断末位是否为0,若是末位为0,则将数组长度-1,注意,这边判断不需要用while循环,用if语句即可。
  6. 逆序输入整型数组。

代码实现

#include <iostream>
#include <string>
using namespace std;
string str1,str2;
int a[210],b[210],c[210];
int len1,len2;
int main(){
	cin >> str1;
	cin >> str2;
	len1 = int(str1.size());
	len2 = int(str2.size());
	if(len1 < len2){
	    for(int i = 1; i <= len2-len1; i ++){
	        str1 = "0"+str1;
	    }
	}else{
	    for(int i = 1; i <= len1-len2; i ++){
	        str2 = "0"+str2;
	    }
	}
	len1 = int(str1.size()), len2 = int(str2.size());
	for(int i = 0; i<=len1-1; i ++){
	    a[len1-i] = str1[i] - '0';
	}
	for(int i = 0; i <= len2-1; i ++){
	    b[len2-i] = str2[i] - '0';
	}
	int x = 0;
	int lenc = 1;
	while(lenc <= len1 || lenc <= len2){
	    c[lenc] = a[lenc]+b[lenc]+x;
	    x = c[lenc]/10;
	    c[lenc] %= 10;
	    lenc++;
	}
	c[lenc] = x;
	if(c[lenc] == 0){
	    lenc --;
	}
	for(int i = lenc; i > 0; i --){
	    cout << c[i];
	}
	cout << endl;
}

猜你喜欢

转载自blog.csdn.net/m0_37550202/article/details/88358516