使用三元運算子在 C++ 中查詢最大數的程式


在這個問題中,我們給出了一些數字。我們的任務是建立一個使用三元運算子在 C++ 中查詢最大數的程式

元素可以是:

  • 兩個數字
  • 三個數字
  • 四個數字

程式碼描述 - 在這裡,我們給出了一些數字(兩個或三個或四個)。我們需要使用三元運算子找到這些數字中的最大元素。

讓我們看幾個例子來理解這個問題:

兩個數字

輸入 - 4, 54

輸出 - 54

三個數字

輸入 - 14, 40, 26

輸出 - 40

四個數字

輸入 - 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+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告