算法3.-三个数中求最大最小值

以最小值代码分析:

1.先用a和b比较,得到a、b中较小的那个数,再和c比较,最后得到最小值

1
2
3
4
5
6
7
int max(int a,int b,int c)
{
if(a<b)
return a<c?a:c;
else
return b<c?b:c;
}

2.三个数的大小无非三种情况,a最小,b最小或者c最小,将三种情况直接列出。

1
2
3
4
5
6
7
8
9
int max(int a,int b,int c)
{
if(a<=b && a<=c)
return a;
else if(b<=a && b<=c)
return b;
else if(c<=a && c<=b)
return c;
}

3.先用a、b分别和c比较,得到a、c中的较小和b、c中的较小,两个较小比较得到三个数中的最小

1
2
3
4
int max(int a,int b,int c)
{
return a<b?(a<c?a:c):(b<c?b:c);
}

4.先用a和b比较,得到a、b中较小的那个数,再和c比较,最后得到最小值。

这一条是1.的三目运算符的实现

1
2
3
4
int max(int a,int b,int c)
{
return (a<b?a:b)<c?(a<b?a:b):c;
}
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2015-2020 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信