问题: 不使用(a+b)/2这种方式,求两个数的平均值
思路: 说到求平均值,也就是不使用除法运算,我们知道位运算右移一位相当于除2.
实现代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int Average(int a, int b) {
int c;
c = a + b;
c = (c >> 1); //通过右移一位运算,得出平均值
return c;
}
int main() {
int a, b, ret;
scanf("%d %d", &a, &b);
ret = Average(a, b);
printf("%d与%d的平均值为:%d\n", a, b, ret);
system("pause");
return 0;
}
运行结果: