本文主要是介绍高精度 加 减 乘,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Add
#include<stdio.h>
#include<math.h>
#include<memory.h>
#include<iostream>
using namespace std;
#define M 100
void add(char* s1, char* s2, char* res)
{//需要两个字符串参数&&无返回值int num1[M], num2[M];int i, j, len1, len2,n,t;memset(num1, 0, M*sizeof(int));memset(num2, 0, M*sizeof(int));//char转换成intlen1 = strlen(s1);len2 = strlen(s2);for (i = len1 - 1, j = 0; i >= 0; i--) {num1[j++] = s1[i] - '0';}for (i = len2 - 1, j = 0; i >= 0; i--) {num2[j++] = s2[i] - '0';}//加法运算for (i = 0; i < M; i++) {num1[i] += num2[i];if (num1[i] > 9) {num1[i] -= 10;num1[i + 1]++;}}//找到第一个不是0的数for (i = M - 1; i >= 0 && num1[i] == 0; i--) {;}num1[i + 1] = -1;//判断结果为0的情况n = i + 1;if (n == 0) {num1[0] = 0;num1[1] = -1;}else {//倒置for (i = 0; i < n / 2; i++) {int temp = num1[i];num1[i] = num1[n - i - 1];num1[n - i - 1] = temp;}}//int转换成charfor (i = 0; num1[i] != -1; i++) {res[i] = num1[i] + '0';}res[i] = 0;
}int main() {char s1[M], s2[M], res[M];cin >> s1 >> s2;Add(s1, s2, res);cout << res << endl;return 0;
}
自己写的有点复杂,以下会更有效的
/** 高精度加法* 输入a,b* 结果储存在a中
*/
void add(char *a, char *b)
{int i, j, inc = 0, s, k;int len1 = strlen(a);//cal the length of a,bint len2 = strlen(b);strrev(a);//reverse string a,b strrev(b);k = 0;while (i < len1&&j < len2) {s = (a[i] & 0xf) + (b[i] & 0xf) + inc;a[k++] = (s % 10) + '0';//add b to ainc = s / 10;//store the carry i++; j++;}//length of a is greater than b while (i < len1) {s = (a[i] & 0xf) + inc;a[k++] = (s % 10) + '0';inc = s / 10;i++;}//length of b is greater than a while (j < len2) {s = (b[j] & 0xf) + inc;a[k++] = (s % 10) + '0';inc = s / 10;j++;}//at last,if the carry is not 0,store it into a if (inc) {a[k++] = inc + '0';}a[k] = 0;strrev(a);
}
Sub
仿照加法写个减法
//高精度数减法
void sub(char* s1, char* s2, char* ans)
{ //s1>s2int i = 0, j = 0, len1, len2, s;len1 = strlen(s1);len2 = strlen(s2);strrev(s1);strrev(s2);while (j < len2) {s = s1[i] - s2[j];if (s < 0) {s = s + 10;s1[i + 1]--;}ans[i] = s + '0';i++; j++;}while (i < len1) {ans[i] = s1[i];i++;}while (ans[i-1] == '0') {i--;}ans[i] = 0;strrev(ans);
}
multiple
//高精度乘法
void multiple(char* a, char* b, char* res)
{int i, j, len1, len2,inc;len1 = strlen(a);len2 = strlen(b);int x[2*N];memset(x, 0, 2*N);//一定要初始化strrev(a);strrev(b);//对应位相乘for (i = 0; i < len1; i++) {for (j = 0; j < len2; j++) {x[i + j] += (a[i] & 0xf) * (b[j] & 0xf);}}//进位运算&int转换成charfor (i = 0, inc = 0; i <= len1 + len2 - 2; i++) {x[i] += inc;res[i] = (x[i] % 10) + '0';inc = x[i] / 10;}if (inc) {res[i++] = inc + '0';}res[i] = 0;strrev(res);
}
这篇关于高精度 加 减 乘的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!