21xrx.com
2025-04-01 19:27:37 Tuesday
文章检索 我的文章 写文章
C++如何比较三个数大小?
2023-07-03 00:28:30 深夜i     148     0
C++ 比较 三个数 大小

在C++中比较三个数的大小有多种方法。下面是三种常用的方法:

1. 使用if语句来比较三个数的大小。这种方法需要使用多个if语句进行比较,比较代码会比较冗长,但是易于理解。

#include <iostream>
using namespace std;
int main() {
 int a, b, c;
 cin >> a >> b >> c;
 
 if (a > b) {
  if (a > c)
   cout << "a is the largest." << endl;
  
  else
   cout << "c is the largest." << endl;
  
 }
 else {
  if (b > c)
   cout << "b is the largest." << endl;
  
  else
   cout << "c is the largest." << endl;
  
 }
 
 return 0;
}

2. 使用三目运算符(?:)进行比较。这种方法比较简单,代码量也比较少,但是可读性可能会稍差。

#include <iostream>
using namespace std;
int main() {
 int a, b, c;
 cin >> a >> b >> c;
 
 int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
 
 cout << max << " is the largest." << endl;
 
 return 0;
}

3. 使用STL中的max函数进行比较。这种方法需要引入头文件 ,然后直接调用max函数即可。代码简洁,但是可能会稍微慢一些。

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
 int a, b, c;
 cin >> a >> b >> c;
 
 int max_val = max(a);
 
 cout << max_val << " is the largest." << endl;
 
 return 0;
}

以上是C++比较三个数大小的三种方法,使用哪一种方法取决于个人习惯和具体情况。

  
  

评论区