//此题重在理解两个数相乘的算法,
4#include <stdio.h>
5#include <stdlib.h>
6#include <string.h>
7#define MAXSIZE 201
8int main()
9{
10 char line1[MAXSIZE];
11 char line2[MAXSIZE];
12 int a1[MAXSIZE];
13 int a2[MAXSIZE];
14 int product[MAXSIZE];
15
16 while ( scanf ("%s%s", line1, line2) != EOF )
17 {
18 int len1, len2;
19 len1 = strlen (line1);
20 len2 = strlen (line2);
21
22 memset (a1, 0, sizeof (a1));
23 memset (a2, 0, sizeof (a2));
24 memset (product, 0, sizeof (product));
25
26 //对负数的处理
27 if ( line1[0] == '-' || line2[0] == '-' )
28 return 0;
29 //对 0 和 其它数相乘的处理
30 int mark = 0;
31 if ( ( !strcmp (line1,"0") ) || ( !strcmp (line2, "0") ) )
32 {
33 printf ("%d", 0);
34 }
35
36 //将字符数转化为数字
37 int j = 0;
38 for (int i = len1 - 1; i >= 0; i--)
39 {
40 a1[j++] = line1[i] - '0';
41 }
42 int k = 0;
43 for (int i = len2 - 1;i >= 0; i--)
44 {
45 a2[k++] = line2[i] - '0';
46 }
47
48 //乘法算法
49 for (int i = 0; i < len2; i++)
50 for (int j = 0; j < len1; j++)
51 {
52 product[i + j] += a1[j] * a2[i];
53 }
54
55 //处理进位
56 for (int i = 0; i < MAXSIZE; i++ )
57 {
58 if ( product[i] >= 10 )
59 {
60 product [i + 1] += product [i] / 10;
61 product [i] = product[i] % 10;
62 }
63 }
64
65 //输出处理
66 bool target = false;
67 for (int i = MAXSIZE - 1; i >= 0; i--)
68 {
69 if (target)
70 printf ("%d", product[i]);
71 else if (product[i])
72 {
73 printf ("%d", product[i]);
74 target = true;
75 }
76 }
77 printf ("\n");
78 }
79 //system ("pause");
80 return 0;
81}
82
以及特殊数据的考虑 :如 含有 0 和 负数时
posted on 2010-08-09 13:08
雪黛依梦 阅读(380)
评论(0) 编辑 收藏 引用 所属分类:
大数