問題描述:
Calculate A × B
Input
The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line.
Output
For each pair of input integers a and b you should output the sum of a and b in one line, and with one line of output for each line in input.
Input and output are the same with problem 1001.
But A and B may be big integer.
The biggest integer is less than 10^500.
#include
#include
#include
#include
#define N 500
void reverse(char *num,char *newnum){/*reverse()函數用於顛倒字符串,將num字符串以反順序存放到newnum中,目的是將便於之后從個位進行計算*/
int length=strlen(num);
int i,j;
for(i=0,j=length-1;i
newnum[i]=num[j];
}
}
void transform(char* num_char,int *num_int){ /*transform()函數用於將num_char字符串轉換成整數字符串,便於進行數字計算*/
int len=strlen(num_char);
int i;
char *newchar;
newchar=(char*)malloc(sizeof(char)*len);
reverse(num_char,newchar);
for(i=0;i
num_int[i]=newchar[i]-'0';
}
}
void multiply(char *num1,char *num2,int *result){ /*multiply()函數將傳入的兩個大數的字符串形式在內部轉換后相乘,將結果返回給整數數組*/
int i,j,k;
int len1=strlen(num1);
int len2=strlen(num2);
int numint1[len1],numint2[len2];
transform(num1,numint1);
transform(num2,numint2);
int len3=len2+len1;
for(i=0;i
result[i]=0;
}
for(i=0;i
for(j=0;j
result[i+j]+=numint1[i]* numint2[j];
}
}
for(i=0;i
result[i+1]+=(result[i]/10);
result[i]=(result[i]%10);
}
}
void display(int *result)/*將整個整數數組顯示,其中數組前面的0不顯示,這樣達到顯示正確結果的目地*/
{
int i=2*N-1;
while(result[i]==0)
{
i--;
}
for(i;i>=0;i--)
{
printf("%d",result[i]);
}
printf("\n");
}
int main(void)
{
char number1[N],number2[N];
int result[2*N];
int i,j;
while(scanf("%s%s",number1,number2)==2)
{
for(i=0;i<2*N;i++){
result[i]=0;
}
multiply(number1,number2,result);
display(result);
}
return 0;}這道題雖然沒那么難,但是我花了一個多星期才陸陸續續寫出來,對每個函數編寫了測試模塊(原諒我是真的菜,在參考了別人的代碼之后,還是不能正確寫出來,后面大多數時間都在調試...,對每個函數編寫測試模塊的原因是我找不出哪里除了問題,一直說Segementation fault.能寫出來是真的開心,后面再參考其他更先進的算法)