高精度加法的c语言实现

来源:互联网 发布:工商网络监管情况 编辑:程序博客网 时间:2024/05/16 05:35

本篇为高精度加法的计算,接下来我还会去写高精度乘法的计算

一、高精度运算的概念

高精度运算其实就是参与运算的数完全超出基本数据类型所能表示的范围的运算(例如int型范围就是 - 2147483648 ~+ 2147483647)
所以如果想求较大数的话就要创建新的数据类型


二、数据类型的选取

我选择的是int型数组,这样比较便于计算和理解


三、代码


其中a和b我是通过随机数来赋值
//authorsummer_awn//date2017/6/20#include<iostream>#include<time.h>#define lenth_a 200#define lenth_b 200using namespace std;//计算a+bvoid main() {srand((unsigned)time(NULL));int * a = new int[lenth_a];//数组a            ******for (int i = 0; i < lenth_a; ++i) {a[i] = rand() % 10;}cout << "a=";for (int i = lenth_a - 1; i >= 0; --i) {//输出acout << a[i];}cout << endl;cout << endl;int * b = new int[lenth_b];//数组b            ******for (int i = 0; i < lenth_a; ++i) {b[i] = rand() % 10;}cout << "b=";for (int i = lenth_b - 1; i >= 0; --i) {//输出bcout << b[i];}cout << endl;cout << endl;int lenth_result;//结果的长度enif (lenth_a > lenth_b) lenth_result = lenth_a + 1;else lenth_result = lenth_b + 1;//通过一个判断来确定结果的长度int * a2 = new int[lenth_result];//a2***********int * b2 = new int[lenth_result];//b2***********memcpy(a2, a, sizeof(int)*lenth_a);//memset(a2 + lenth_a, 0, sizeof(int)*(lenth_result - lenth_a));memcpy(b2, b, sizeof(int)*lenth_b);memset(b2 + lenth_b, 0, sizeof(int)*(lenth_result - lenth_b));delete(a);delete(b);int * result = new int[lenth_result];//result*********result[0] = a2[0] + b2[0];for (int i = 1; i < lenth_result - 1; ++i) {result[i] = a2[i] + b2[i] + result[i - 1] / 10;result[i - 1] = result[i - 1] % 10;}result[lenth_result - 1] = result[lenth_result - 2] / 10;result[lenth_result - 2] = result[lenth_result - 2] % 10;delete(a2);delete(b2);cout << "结果=";for (int i = lenth_result - 1; i >= 0; --i) {cout << result[i];}cout << endl;system("pause");delete(result);}



四、结果

结果有截图,未验证(因为懒)



总结一下,觉得自己的方法还是挺烂的,有好的建议欢迎留言