不使用(a+b)/2这种方式,求两个数的平均值

通常我们求平均值习惯于利用(a+b)/2这种方式,但在我们的编程当中,如果数据过大,a+b在计算过程中可能会出现数据溢出的情况,从而导致结果出错,相反如果我们换一种思路,就可以避免这种情况,比如,我们可以利用大的数减去小的数,从大数比小数多的这部分中取出一半给小数,这样也是求平均数的一种放法,相应代码如下:

#include <stdio.h>
#include <stdlib.h>
int Average(int x, int y){
	if (x > y){
		return (x - y) / 2 + y;
	}
	else {
		return (y - x) / 2 + x;
	}
}
int main(){
	int a = 10;
	int b = 20;
	printf("%d\n",Average(a,b));
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44781107/article/details/89357672