C + + Internship high-precision addition
Recently encountered a C + + implementation of high-precision addition problem, high-precision problems are often ten complex but found that the law found not so complex, here I realized an integer high-precision addition, the main need to pay attention to the following points:
1: Enter the required input data in the form of a character array, create a character array, set up an array of integers, and then map each one to achieve the input of the data, it should be noted that when the implementation of the character to the digital mapping, should be subtracted from the corresponding ASCII offset value, that is, 48.
2: In order to simulate our carry-on simulation operation in the paper, we put the character array back into the integer array, the following lines of code to achieve this operation.
3: Implementation of carry addition, which is the core part of the entire code, needs to be carefully understood by the reader, seriously, often need to think repeatedly, easy to forget
4: Reverse output data. Because our addition is to reverse the array, then from left to right to add, after the addition, the number of digits on the left, so you need to reverse the output
Here's the whole code:
#include <iostream>#include<cstdio>#include<cstring>using namespacestd; intMain () {Chara1[ -],b1[ -]; inta[ -],b[ -],c[ -]; inta1_len,b1_len,lenc,i,x; Memset (A,0,sizeof(a)); memset (b,0,sizeof(b)); Memset (c,0,sizeof(c)); Gets (A1); Gets (B1); //input addend and be addendA1_len=strlen (A1); B1_len=strlen (B1); for(i=0; i<=a1_len-1; i++) {A[a1_len-i]=a1[i]- -;//put the operand into a array } for(i=0; i<=b1_len-1; i++) {B[b1_len-i]=b1[i]- -;//put the operand into the B array} Lenc=1; X=0; while(Lenc <=a1_len | | Lenc <=B1_len) {C[lenc]=a[lenc]+b[lenc]+x;//two numbers addedx=c[lenc]/Ten;//the bit to go inc[lenc]=c[lenc]%Ten;//the number after roundinglenc++;//array subscript plus 1} C[lenc]=x; if(c[lenc]==0) {Lenc--;//handling the highest rounding } for(i=lenc;i>=1; i--) {cout<<c[i];//Output Results} cout<<Endl; return 0; }
Using C + + for high-precision addition