日常遇到较多的时间使用都是比较两个数的最大值 或者最小值,这两个处理过程很简单,都可以使用 宏MAX/MIN 来计算。
今天碰到获取三个数的中间值使用情况,花费些时间思考,将个人思考的两种方法进行总结记录。
方法
-
方法一 将三个数相加,然后减去三个数中的最大值和最小值,余下的就是中间值。 /* Macros for min/max. */
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
?
/* sum of three number largest smallest */
#define MID_1(a,b,c) ((a) + (b) + (c) - MAX(MAX(a,b),c) - MIN(MIN(a,b),c))* -
方法二 采用简单的逻辑判断,依次进行abc 三者之间的关系判断,直至获取到中间值。如下为逻辑代码: if a > b
? if a<c
? /* c>a>b */
? mid = a
? else/* a> b , a > c */
? /\* *Whichever is greater between b and C is the middle value \**/
? if b > c
? /* a>b>c */
? mid = b
? else
? /* a>c>b */
? mid = c
else/* a <b*/
? if a > c
? /* b>a>c */
? mid = a
? else/*a< b , a < c*/
? /\**Whichever is smaller between b and C is the middle value\**/
? if b > c
? /* a>c>b */
? mid = c
? else
? /* a>b>c */
? mid = b
总体测试程序
abc 三个数中,每个数与其他数的关系都是大于/等于/小于 ,因此测试用例总共有3^3 = 27 种。
#include<stdio.h>
?
/* Macros for min/max. */
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
?
/* sum of three number largest smallest */
#define MID_1(a,b,c) ((a) + (b) + (c) - MAX(MAX(a,b),c) - MIN(MIN(a,b),c))
#define MID_2(a,b,c) ((a)>(b)?((a)<(c)?(a):(b)>(c)?(b):(c)):((a)>(c)?(a):(b)>(c)?(c):(b)))
?
?
int main()
{
int num[3] = {1,2,3};
int count = 3;
int i = 0, j = 0, k = 0;
int mid1 = -1,mid2 = -1;
?
for(i = 0;i <count; i ++)
for(j = 0; j < count; j++)
for (k = 0; k < count; k++)
{
mid1 = MID_1(num[i], num[j], num[k]);
mid2 = MID_2(num[i], num[j], num[k]);
printf("MID(%d,%d,%d) => MID_1 = %d, MID_2 = %d, MID_1 %s MID_2\n",num[i],num[j],num[k],mid1,mid2,mid1==mid2?"==":"!=");
}
?
return 0;
}
结果如下:
MID(1,1,3) => MID_1 = 1, MID_2 = 1, MID_1 == MID_2
MID(1,2,1) => MID_1 = 1, MID_2 = 1, MID_1 == MID_2
MID(1,2,2) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(1,2,3) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(1,3,1) => MID_1 = 1, MID_2 = 1, MID_1 == MID_2
MID(1,3,2) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(1,3,3) => MID_1 = 3, MID_2 = 3, MID_1 == MID_2
MID(2,1,1) => MID_1 = 1, MID_2 = 1, MID_1 == MID_2
MID(2,1,2) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(2,1,3) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(2,2,1) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(2,2,2) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(2,2,3) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(2,3,1) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(2,3,2) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(2,3,3) => MID_1 = 3, MID_2 = 3, MID_1 == MID_2
MID(3,1,1) => MID_1 = 1, MID_2 = 1, MID_1 == MID_2
MID(3,1,2) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(3,1,3) => MID_1 = 3, MID_2 = 3, MID_1 == MID_2
MID(3,2,1) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(3,2,2) => MID_1 = 2, MID_2 = 2, MID_1 == MID_2
MID(3,2,3) => MID_1 = 3, MID_2 = 3, MID_1 == MID_2
MID(3,3,1) => MID_1 = 3, MID_2 = 3, MID_1 == MID_2
MID(3,3,2) => MID_1 = 3, MID_2 = 3, MID_1 == MID_2
MID(3,3,3) => MID_1 = 3, MID_2 = 3, MID_1 == MID_2
?可以看到两种结果计算的中间值是一样,结果均正确。
|