C語言實現(xiàn)高精度加法
本篇為高精度加法的計算,接下來我還會去寫高精度乘法的計算。
一、高精度運算的概念
高精度運算其實就是參與運算的數(shù)完全超出基本數(shù)據(jù)類型所能表示的范圍的運算(例如int型范圍就是 - 2147483648 ~+ 2147483647)
所以如果想求較大數(shù)的話就要創(chuàng)建新的數(shù)據(jù)類型
二、數(shù)據(jù)類型的選取
我選擇的是int型數(shù)組,這樣比較便于計算和理解
三、代碼
其中a和b我是通過隨機數(shù)來賦值
//author summer_awn //date 2017/6/20 #include<iostream> #include<time.h> #define lenth_a 200 #define lenth_b 200 using namespace std; //計算a+b void main() { srand((unsigned)time(NULL)); int * a = new int[lenth_a];//數(shù)組a ****** for (int i = 0; i < lenth_a; ++i) { a[i] = rand() % 10; } cout << "a="; for (int i = lenth_a - 1; i >= 0; --i) {//輸出a cout << a[i]; } cout << endl; cout << endl; int * b = new int[lenth_b];//數(shù)組b ****** for (int i = 0; i < lenth_a; ++i) { b[i] = rand() % 10; } cout << "b="; for (int i = lenth_b - 1; i >= 0; --i) {//輸出b cout << b[i]; } cout << endl; cout << endl; int lenth_result;//結(jié)果的長度en if (lenth_a > lenth_b) lenth_result = lenth_a + 1; else lenth_result = lenth_b + 1;//通過一個判斷來確定結(jié)果的長度 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 << "結(jié)果="; for (int i = lenth_result - 1; i >= 0; --i) { cout << result[i]; } cout << endl; system("pause"); delete(result); }
四、結(jié)果
結(jié)果有截圖,未驗證(因為懶)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C/C++ Qt 基本文件讀寫的基本使用(2種實現(xiàn))
文件的讀寫是很多應(yīng)用程序具有的功能,本文主要介紹了兩種實現(xiàn)方法,第一種使用QFile類的IODevice讀寫功能直接讀寫,第二種是利用 QFile和QTextStream結(jié)合起來,用流的方式進行文件讀寫2021-11-11通過c++的sort函數(shù)實現(xiàn)成績排序功能
這篇文章主要介紹了通過c++的sort函數(shù)實現(xiàn)成績排序,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02C語言數(shù)據(jù)結(jié)構(gòu)之棧與隊列的相互實現(xiàn)
這篇文章主要為大家詳細介紹了如何利用C語言相互實現(xiàn)數(shù)據(jù)結(jié)構(gòu)中的棧與隊列,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2022-07-07