题目要求:
设计一大整数相乘的函数,函数原型int multiply(char *strNum1,char *strNum2, char *strRslt),strNum1是字符串表示的被乘数,strNum2是字符串表示的乘数,strRslt用来存放乘积结果的字符串。
例如:strNum1 = “2345678901234”;
strNum2 = "23456789"
乘积结果,strRslt="55022095047997777626"
函数实现:
#include <stdio.h> #include <stdlib.h> #include <string.h> int multiply(char *strNum1,char *strNum2, char *strRslt) { int i,j,carry,t,tt; int len1, len2; int rslt_index = 0; if(strNum1 == NULL || strNum2 == NULL || strRslt == NULL) return -1; len1 = strlen(strNum1); len2 = strlen(strNum2); memset(strRslt, 0 ,len1+len2);//把存放结果的空间先清零 for(i = 0; i < len2; i++) { carry = 0; for(j = 0; j < len1; j++) { t = (strNum1[len1-1-j]-'0')*(strNum2[len2-1-i]-'0')+carry;//从最低位开始计算 if(0 == t) continue; rslt_index = j+i; tt = strRslt[rslt_index] + t; strRslt[rslt_index] = tt % 10; carry = tt / 10; } if(carry > 0) { strRslt[++rslt_index] += carry; } } //反串 for(i = 0; i <=rslt_index/2; i++) { t = strRslt[i] + '0'; strRslt[i] = strRslt[rslt_index-i] + '0'; strRslt[rslt_index-i] = t; } return 0; } int main(void) { char a[20] = {0}; char b[20] = {0}; char result[50] = {0}; printf("Pls input first integer:"); scanf("%s",a); printf("Pls input second integer:"); scanf("%s",b); multiply(a, b, result); printf("result is:%s\r\n",result); return 0; }