In a computer, due to the limited bit width of the processor, only decimal integer addition and subtraction with limited precision can be processed. for example, in a 32-bit width processor computer, the operations and results involved in the operation must be between-231 ~ Between 231-1. If you need to add a larger range of decimal integers, you need to use special methods, such as saving the operands and results using strings, and using a bitwise operation.
In a computer, due to the limited bit width of the processor, only decimal integer addition and subtraction with limited precision can be processed. for example, in a 32-bit width processor computer, the operations and results involved in the operation must be between-231 ~ Between 231-1. If you need to add a larger range of decimal integers, you need to use special methods, such as saving the operands and results using strings, and using a bitwise operation. For example:
9876543210 + 1234567890 =?
Let the string num1 = "9876543210", string num2 = "1234567890", and save the result in the string result. Programming is required to implement the preceding high-precision decimal addition.
# Include
# Include
Int NumAdd (const char * first, const char * second, char * result, int resultlen) {int numlen [2]; numlen [0] = strlen (first ); numlen [1] = strlen (second); int maxlen; maxlen = numlen [0]> numlen [1]? Numlen [0]: numlen [1]; if (resultlen <maxlen + 1) return-1; int n; int byteValue [2]; int curByteResult; int addByteResult; curByteResult = addByteResult = 0; // loop from left to right (n = 0; n
= 0) byteValue [0] = first [n]-'0'; else byteValue [0] = 0; if (numlen [1]> = 0) byteValue [1] = second [n]-'0'; else byteValue [1] = 0; curByteResult = byteValue [0] + byteValue [1]; if (curByteResult> = 10) {curByteResult-= 10; addByteResult = 1; if (n = 0) {result [0] = '1'; ++ result ;} else {++ result [n-1]; // processing carry} result [n] = '0' + curByteResult;} else {result [n] = '0' + curByteResult; addByteResult = 0;} result [n] = 0; return 1;} int main () {char szstr1 [] = "9876543210"; char szstr2 [] = "1234567890 "; char result [100]; NumAdd (szstr1, szstr2, result, 100); printf ("result is % s", result); return 0 ;}
This article is available at http://www.nowamagic.net/librarys/veda/detail.