求兩個字串的乘積,結果存到字串中,例如字串一中存的“657891”,字串二中存的“521”
輸出342761211
#include<stdio.h>#include<malloc.h>#include<string.h>#include<assert.h>void mul(char *Input1, int n, char *Input2, int m,char *Output);int main(){int n, m;int i = 0;char Input1[100];char Input2[100];char *Output;char *Result;gets(Input1);gets(Input2);n = strlen(Input1);m = strlen(Input2);Output = (char *)malloc(sizeof(char) * (m+n+1));assert(n>0 && m > 0 && Output != NULL);mul(Input1, n, Input2, m,Output);Result = Output;while(*Result == '0' && Result < Output+(m+n-1))//如果結果是0,輸出一個0Result++;printf("%s\n", Result); free(Output); return 0;}void mul(char *Input1, int n, char *Input2, int m,char *Output){int i = 0;int j = 0;char *endIn1 = Input1+n-1;char *endIn2 = Input2 + m-1;char *endOut = Output + m+n-1;char *ptemp;int overflow = 0;for(i = 0; i < n+m; ++i)Output[i] = '0';Output[i] = '\0';while(endIn2 >= Input2) //從乘數的最後一位開始依次與乘數相乘{ptemp = endOut; while(endIn1 >= Input1) {i = *endIn2 - '0';j = *endIn1 - '0';*ptemp += (i*j % 10 + overflow); //output原來的值 + 進位 + 這次乘的結果(可能大於10)overflow = i*j/10 + (*ptemp - '0')/10;//進位的值*ptemp = (*ptemp-'0')%10 + '0'; //output 的真實值ptemp--; //依次計算output的每一位的值endIn1--; }if(overflow != 0) //最後是不是還有進位*ptemp = overflow + '0';overflow = 0;endIn1 = Input1+n-1;endOut--;//每一輪迴圈相乘之後,與Output的最低位相加的時候也要左移一位endIn2--;}Output[m+n] = '\0';}