在C ++中使用最少比较的三分之三
在本节中,我们将看到如何比较三个给定值的中间值。因此,如果给出三个数字,如(10,30,20),则它将找到20,因为这是中间元素。首先让我们看一下算法,然后将其实现为C++代码。
算法
middle_of_three(a, b, c):
Input: Three numbers a, b and c
Output: The middle of these three
Begin
if a > b, then
if b > c, then
return b
else if a > c, then
return c
else
return a
else
if a > c, then
return a
else if b > c, then
return c
else
return b
End示例
#include <iostream>
using namespace std;
int mid_three(int a, int b, int c) {
if (a > b) {
if (b > c)
return b;
else if (a > c)
return c;
else
return a;
} else {
if (a > c)
return a;
else if (b > c)
return c;
else
return b;
}
}
main() {
int a = 10, b = 30, c = 20;
cout << "Middle Out of Three "<< mid_three(a, b, c);
}输出结果
Middle Out of Three 20