作业帮 > 综合 > 作业

C语言课程设计大数乘法和除法

来源:学生作业帮 编辑:神马作文网作业帮 分类:综合作业 时间:2024/11/17 21:15:01
C语言课程设计大数乘法和除法
用字符储存数字进行的大数运算 1) 用一个整型数组表示一个大数,数组的每个元素存储大数的一位数字,则实际的大数d表示为:d=a[k]×10 k-1 +a[k-1]×10 k-2 +…+a[2]×10+a[1] 其中a[0]保存该大数的位数.2) 实现两个大数相乘; 在此基础上实现两个大数相除
C语言课程设计大数乘法和除法
#include #include #define MAXCHAR 20000 void Add (char *ch1 , char *ch2 , char *ch3) {// ch3 = ch1 + ch2; int len1 = strlen (ch1) , len2 = strlen (ch2) , len3 , i , tmp , num1[MAXCHAR] , num2[MAXCHAR] , num3[MAXCHAR]; memset (num1 , 0 , sizeof(num1)); memset (num2 , 0 , sizeof(num2)); memset (num3 , 0 , sizeof(num3)); for (i=len1-1;i>=0;i--) num1[len1-1-i] = ch1[i] - 48; for (i=len2-1;i>=0;i--) num2[len2-1-i] = ch2[i] - 48; i = 0 , tmp = 0 , len3 = len1 > len2 ? len1 : len2; while (i < len3) { num3[i] = num1[i] + num2[i] + tmp; tmp = 0; if (num3[i] >= 10) { tmp = num3[i]/10; num3[i] %= 10; } i ++; } if (tmp != 0) { num3[i] = tmp; i ++; } len3 = i; for (i=len3-1;i>=0;i--) ch3[len3-1-i] = num3[i] + 48; ch3[len3] = '\0'; return ; } void Minus (char *ch1 , char *ch2 , char *ch3) { // 保证 ch1 > ch2 : ch3 = ch1 - ch2 int i , tmp , len1 = strlen (ch1) , len2 = strlen (ch2) , len3 , num1[MAXCHAR] , num2[MAXCHAR] , num3[MAXCHAR]; memset (num1 , 0 , sizeof(num1)); memset (num2 , 0 , sizeof(num2)); memset (num3 , 0 , sizeof(num3)); for (i=0;i 1 && num3[len3-1] == 0) len3 --; for (i=0;i=0;i--) num1[len1-1-i] = ch1[i] - 48; for (i=len2-1;i>=0;i--) num2[len2-1-i] = ch2[i] - 48; for (i=0;i 1 && num3[len3-1] == 0) len3 --; for (i=0;i ch2 return 1; ch1 < ch2 return -1; ch1 == ch2 return 0; int i , len1 = strlen (ch1) , len2 = strlen (ch2); if (len1 > len2) return 1; if (len2 > len1) return -1; for (i=0;i ch2[i]) return 1; if (ch1[i] < ch2[i]) return -1; } return 0; } void Div (char *ch1 , char *ch2 , char *ch3) {//保证ch1>ch2 && ch2 != 0 : ch3 = ch1/ch2 , ch1 = ch1%ch2 , 需要支持函数:cmp () , Minus (); int i , len1 , len2 , tmp; char ch4[MAXCHAR] , ch5[MAXCHAR]; ch3[0] = '0' , ch3[1] = '\0'; while (cmp (ch1 , ch2) >= 0) { len1 = strlen (ch1) , len2 = strlen (ch2); tmp = len1-len2-1 > 0 ? len1-len2-1 : 0; ch4[0] = '1'; memcpy (ch5 , ch2 , (len2+1)*sizeof(char)); for (i=0;i= ch2 : ch1 %= ch2 , 需要支持函数:Minus () , cmp (); int i , len1 , len2 , tmp; char ch3[MAXCHAR]; while (cmp (ch1 , ch2) >= 0) { len1 = strlen (ch1) , len2 = strlen (ch2); tmp = len1-len2-1 > 0 ? len1-len2-1 : 0; memcpy (ch3 , ch2 , (len2+1)*sizeof(char)); for (i=0;i