Average: Given two numbers a and b, find the average;
Analysis: The consistent algorithm in mathematical operations is (a+b)/2, but this algorithm has certain defects in C language. When a and b are large enough, the sum of a and b will overflow, so We don't get the results we want. There are corresponding operators in c language that can achieve the effect of averaging, such as: >> (right shift), & as AND, ^ (bitwise exclusive or).
1. A flawed algorithm (a+b)/2
example:
intmain()
{
int a=4,b=2;
int ret=0;
ret=(a+b)/2;
printf("a+b=%d\n",ret);
return 0;
}
The result of this program running is 3, there is no problem, it satisfies the algorithm of finding the average in the mathematical operation, but when we assign the values of a and b to 2147483647,
The output result is -1; at this time, the sum of a and b is twice 2147483647, but the maximum number stored in the compiler is 2147483647, so an overflow occurs, and the output result is -1.
2、a+(b-a)/2
example:
intmain() { int a=2147483647,b=2147483647; /*int a=2,b=4;*/ int ret=0; ret=a+(b-a)/2; printf("a+b=%d\n",ret); return 0; }
This program first finds the difference between b and a and divides it by 2, and then adds a; this algorithm ensures that the program will not overflow during the operation. The average is obtained even when the values of a and b are large.
3. Use the >> right shift operator
example:
intmain() { int a=2,b=4; int ret=0; ret=(a+b)>>1; printf("a+b=%d\n",ret); return 0; }This program uses the left shift operator to achieve the purpose of dividing by 2 to find the average of a and b. The right shift operator is to move all the bits of a number to the right by a number of bits. Here we move the sum of a and b to the right by 1 bit, and the high bit goes to the low bit, so as to achieve the purpose of dividing by 2. Let's take a look at the implementation process:
3. Use & bitwise AND and >> bitwise XOR
example:
intmain() { int a=2,b=4; int ret=0; ret=(a&b)+((a^b)>>1); printf("a+b=%d\n",ret); return 0; }
The rule of the bitwise AND operator is: the binary bits of two numbers are 1 for the same and 0 for the difference. At this time, the result of the bitwise AND can leave the same binary bits, and the different binary positions are 0 to achieve the result of adding and dividing the same binary bits by 2; bitwise XOR operator: the binary bits of two numbers, the difference is 1, the same is 0 . At this time, the result of bitwise XOR leaves different binary bits, the same binary position is 0, and is shifted to the right by 1 bit to achieve the result of adding and dividing different binary bits by 2. Implementation process:
operation result: