在計算機中,由於處理器位寬限制,只能處理有限精度的十進制整數加減法,比如在32位處理器計算機中,參與運算的操作數和結果必須在**之間。如果需要進行更大範圍的十進制整數加法,需要使用特殊的方式實現,比如使用字符串保存操作數和結果,採取逐位運算的方式。比如下面問題:
9876543210 + 1234567890 =?
讓字符串 num1 = "9876543210",字符串 num2 = "1234567890",結果保存在字符串result中。要求編程實現上述高精度的十進制加法。
01 |
#include<stdio.h> |
02 |
#include<string.h> |
03 |
int NumAdd( const char *first, const char *second, char *result, int resultlen) |
04 |
{ |
05 |
int numlen[2]; |
06 |
numlen[0]
= strlen (first); |
07 |
numlen[1]
= strlen (second); |
08 |
int maxlen; |
09 |
maxlen=
numlen[0]> numlen[1] ? numlen[0] : numlen[1] ; |
10 |
|
11 |
if (resultlen<
maxlen + 1) |
12 |
return -1; |
13 |
|
14 |
int n; |
15 |
int byteValue[2]; |
16 |
int curByteResult; |
17 |
int addByteResult; |
18 |
|
19 |
curByteResult=addByteResult=0; |
20 |
21 |
//從左到右進行循環 |
22 |
for (n
= 0; n <maxlen; n++) |
23 |
{ |
24 |
--numlen[0]; |
25 |
--numlen[1]; |
26 |
27 |
if (numlen[0]
>= 0) |
28 |
byteValue[0]
= first[n] - '0' ; |
29 |
else |
30 |
byteValue[0]
= 0 ; |
31 |
|
32 |
if (numlen[1]
>= 0) |
33 |
byteValue[1]
= second[n]- '0' ; |
34 |
else |
35 |
byteValue[1]
= 0 ; |
36 |
|
37 |
curByteResult
= byteValue[0] + byteValue[1]; |
38 |
if (curByteResult>=10) |
39 |
{ |
40 |
curByteResult
-= 10; |
41 |
addByteResult
= 1; |
42 |
|
43 |
if (n==0) |
44 |
{ |
45 |
result[0]
= '1' ; |
46 |
++result; |
47 |
} |
48 |
else |
49 |
{ |
50 |
++result[n-1]; //處理進位 |
51 |
} |
52 |
result[n]
= '0' +curByteResult; |
53 |
} |
54 |
else |
55 |
{ |
56 |
result[n]
= '0' +curByteResult
; |
57 |
addByteResult
= 0; |
58 |
} |
59 |
} |
60 |
result[n]
=0; |
61 |
return 1; |
62 |
} |
63 |
64 |
65 |
int main(
) |
66 |
{ |
67 |
char szstr1[]= "9876543210" ; |
68 |
char szstr2[]= "1234567890" ; |
69 |
char result[100]; |
70 |
|
71 |
NumAdd(szstr1,szstr2,result,100); |
72 |
printf ( "result
is %s " ,result); |
73 |
74 |
return 0; |
75 |
} |