The first method is the most common
average=(a + b) / 2 This way, find the average of two numbers
The second method is
When a<b
averag=a+(b-a)/2
Here is the third method
average=(a&b) + (a^b)>>1
The derivation process is as follows
a + b = (a&b) 2 + (a^b)) ———》average=((a&b)2+(a^b))/2 ————》average=(a&b) + (a^b)>>1
eg:
Two numbers are 15 and 5
15 The low bit of the binary sequence is 1111
5 The low bit of the binary sequence is 0101
After bitwise and (&) operation, we get the same part 0101
After bitwise XOR (^) operation, we get the two different parts 1010
Because the same part has both, multiply by two, add different parts (this is 15+5) and divide by 2 to the average value (10).
0101 is 5, multiplied by 2 is 10, plus 1010 (10) is 20, and then divided by 2 is the average value of 10.
Source code example:
#include<>
#include<>
int average(int a, int b)
{
return (a&b) + ((a^b) >> 1);
}
int main()
{
int num1, num2;
int result;
printf("Please enter two numbers\n");
scanf("%d%d", &num1, &num2);
result = average(num1, num2);
printf("Average is %d\n", result);
system("pause");
return 0;
}