使用三元运算符在 C++ 中查找最大数的程序


在这个问题中,我们给出了一些数字。我们的任务是创建一个使用三元运算符在 C++ 中查找最大数的程序

元素可以是:

  • 两个数字
  • 三个数字
  • 四个数字

代码描述 - 在这里,我们给出了一些数字(两个或三个或四个)。我们需要使用三元运算符找到这些数字中的最大元素。

让我们看几个例子来理解这个问题:

两个数字

输入 - 4, 54

输出 - 54

三个数字

输入 - 14, 40, 26

输出 - 40

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

四个数字

输入 - 10, 54, 26, 62

输出 - 62

解决方案方法

我们将使用三元运算符,针对两个、三个和四个元素来找到四个元素中的最大元素。

实现三元运算符用于:

两个数字 (a, b),

a > b ? a : b

三个数字 (a, b, c),

(a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c)

四个数字 (a, b, c, d),

(a>b && a>c && a>d) ?
   a :
   (b>c && b>d) ?
      b :
      (c>d)? c : d

程序说明了我们针对两个数字的解决方案的工作原理:

示例

 实时演示

#include <iostream>
using namespace std;
int main() {
   int a = 4, b = 9;
   cout<<"The greater element of the two elements is "<<( (a > b) ? a :b );
   return 0;
}

输出

The greater element of the two elements is 9

程序说明了我们针对三个数字的解决方案的工作原理:

示例

 实时演示

#include <iostream>
using namespace std;
int findMax(int a, int b, int c){
   int maxVal = (a>b) ?
   ((a>c) ?
   a : c) :
   ((b>c) ?
   b : c);
   return maxVal;
}
int main() {
   int a = 4, b = 13, c = 7;
   cout<<"The greater element of the two elements is "<<findMax(a, b,c);
   return 0;
}

输出

The greater element of the two elements is 13

程序说明了我们针对四个数字的解决方案的工作原理:

示例

 实时演示

#include <iostream>
using namespace std;
int findMax(int a, int b, int c, int d){
   int maxVal= ( (a>b && a>c && a>d) ? a : (b>c && b>d) ? b : (c>d)? c : d );
   return maxVal;
}
int main() {
   int a = 4, b = 13, c = 7, d = 53;
   cout<<"The greater element of the two elements is "<<findMax(a, b, c, d);
   return 0;
}

输出

The greater element of the two elements is 53

更新于: 2020年9月15日

2K+ 浏览量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告