思路:先是输入两个整数字符串,然后将整数字符串转化为整数,存放在数组里面,再将两个数组相乘,最后相加实现进位的操作。
1 #include <iostream>
2 #include < string .h >3 using namespace std;
4
5 void multiply( const char * a, const char * b);
6
7 int main()
8 {
9 // cout<<"hicjiajia"<<endl;
10
11 string num1,num2; // 初始状态用string来存储大数
12 cout << " 现在,来两个大数吧! " << endl;
13 cin >> num1 >> num2;
14
15 const char * p1 = num1.c_str(); // 将string转为 const char *
16 const char * p2 = num2.c_str(); // 将string转为 const char *
17 multiply(p1,p2);
18
19 system( " pause " );
20 return 0 ;
21 }
22
23 void multiply( const char * a, const char * b)
24 {
25 int i,j,ca,cb, * s;
26 ca = strlen(a);
27 cb = strlen(b);
28 s = ( int * )malloc( sizeof ( int ) * (ca + cb)); // 分配存储空间
29 for (i = 0 ;i < ca + cb;i ++ ) s[i] = 0 ; // 每个元素赋初值0
30
31 for (i = 0 ;i < ca;i ++ )
32 for (j = 0 ;j < cb;j ++ )
33 s[i + j + 1 ] += (a[i] - ' 0 ' ) * (b[j] - ' 0 ' );
34
35 for (i = ca + cb - 1 ;i >= 0 ;i -- ) // 这里实现进位操作
36 if (s[i] >= 10 )
37 {
38 s[i - 1 ] += s[i] / 10 ;
39 s[i] %= 10 ;
40 }
41
42 char * c = ( char * )malloc((ca + cb) * sizeof ( char )); // 分配字符数组空间,因为它比int数组省!
43 i = 0 ; while (s[i] == 0 ) i ++ ; // 跳过头部0元素
44 for (j = 0 ;i < ca + cb;i ++ ,j ++ ) c[j] = s[i] + ' 0 ' ;
45 c[j] = ' \0 ' ;
46 for (i = 0 ;i < ca + cb;i ++ ) cout << c[i];
47 cout << endl;
48 free(s);
49 }
50