使用多种方法求两个数的平均数
来源:互联网 发布:matlab 中文论坛 知乎 编辑:程序博客网 时间:2024/05/18 00:37
在求平均数的方法中,大家最喜欢用的就是先求两个数的和,然后再除以2,得到的结果即为两个数的平均数,实现的代码如下:
<pre name="code" class="cpp">#include<stdio.h>#include<Windows.h>#pragma warning(disable:4996)int main(){int a = 0;int b = 0;printf("Please inter a,b:");scanf("%d %d", &a, &b);printf("%d and %d average is %d\n", a, b, (a + b) / 2);system("pause");return 0;}
若不使用(a+b)/2,若学过移位的童鞋会使用右移的方法,右移一位就相当于除以2,。
int main(){int a = 0;int b = 0;printf("Please inter a,b:");scanf("%d %d", &a, &b);printf("%d and %d average is %d\n", a, b, (a + b) >> 1);system("pause");return 0;}前两种方法都有可能会导致数据的溢出,因此,我们可以将两个数分别右移再相加。
int main(){int a = 0;int b = 0;printf("Please inter a,b:");scanf("%d %d", &a, &b);printf("%d and %d average is %d\n", a, b, (a >> 1)+( b >> 1));system("pause");return 0;}若两数均为奇数,该方法出现错误,于是我们就分情况实现。
int main(){int a = 0;int b = 0;printf("Please inter a,b:");scanf("%d %d", &a, &b);if ((a % 2 == 1) && (b % 2 == 1)){printf("%d and %d average is %d\n", a, b,1 + (a >> 1) + (b >> 1));}else{printf("%d and %d average is %d\n", a, b, (a >> 1) + (b >> 1));}system("pause");return 0;}
但是这种方法又过于繁琐,经过深思熟虑之后,我又想到了一种方法:
int main(){int a = 0;int b = 0;printf("Please inter a,b:");scanf("%d %d", &a, &b);printf("%d and %d average is %d\n", a, b, a + (b - a) / 2);system("pause");return 0;}这种方法既好理解,又简介,还不易出错。
然后要是有人想问,还有没有其他的方法,答案是:当然还有啦!
int main(){int a = 0;int b = 0;printf("Please inter a,b:");scanf("%d %d", &a, &b);printf("%d and %d average is %d\n", a, b, (a&b) + ((a^b) >> 1));system("pause");return 0;}但是最后这种方法不是很好理解,个人建议呢,使用倒数第二种方法。
1 0
- 使用多种方法求两个数的平均数
- 求两个数的平均数
- 多种方法求平均数
- 求两个数最大公约数的多种方法
- 1. 写程序求两个数的平均值(多种方法)
- 只用逻辑运算和移位运算求两个数的平均数
- 用位运算求两个数的平均数
- 用linux求两个数平均数
- 求三个数的平均数
- 求输入数的平均数
- 求几个数的平均数
- 计算两个数的平均数的几种方法解读
- 求平均数的方法以及数的移位
- 递归的方法求平均数
- 求平均数的简单方法
- 不使用中间变量交换两个数. 求平均数考虑溢出
- c++ primer plus 第七章《编程题7.13.1-求两个数的调和平均数》
- 用数组,求五个数的平均数
- NOIP初赛准备:第6课时
- 使用pandas.read_csv()中文乱码问题
- codeforces - E. Devu and Flowers & LightOJ 1124 Cricket Ranking(容斥定理+lucas定理)
- 微信公众平台开发(十二) 发送客服消息
- NOIP初赛准备第7课时
- 使用多种方法求两个数的平均数
- 链表
- 深度学习--基于深度矩阵分解的属性表征学习
- [js移动端交互]移动端交互大纲篇
- java分治算法实现n皇后问题
- vs编译std::numeric_limits::max()编译错误
- NOIP提高组完善程序题目分析
- jQuery Layer 弹层组件
- Codeforces Round #270-D. Design Tutorial: Inverse the Problem(Prime)