目录

  • C++ 输入三个数找出最大值的多种方法
    • 方法 1:使用 if-else 语句
    • 方法 2:嵌套 if 语句
    • 方法 3:使用条件运算符 (三元运算符)
    • 方法 4:使用 std::max 函数
    • 方法 5:使用数组和循环
    • 方法 6:使用函数模板
    • 方法 7:使用指针

C++ 输入三个数找出最大值的多种方法

在 C++ 中,有多种方法可以找出三个数中的最大值。以下是几种常见的实现方式:

方法 1:使用 if-else 语句

#include <iostream>
using namespace std;

int main() {
    int a, b, c;
    cout << "请输入三个整数: ";
    cin >> a >> b >> c;
    
    int max;
    if (a >= b && a >= c) {
        max = a;
    } else if (b >= a && b >= c) {
        max = b;
    } else {
        max = c;
    }
    
    cout << "最大值是: " << max << endl;
    return 0;
}

方法 2:嵌套 if 语句

#include <iostream>
using namespace std;

int main() {
    int a, b, c;
    cout << "请输入三个整数: ";
    cin >> a >> b >> c;
    
    int max;
    if (a > b) {
        if (a > c) {
            max = a;
        } else {
            max = c;
        }
    } else {
        if (b > c) {
            max = b;
        } else {
            max = c;
        }
    }
    
    cout << "最大值是: " << max << endl;
    return 0;
}

方法 3:使用条件运算符 (三元运算符)

#include <iostream>
using namespace std;

int main() {
    int a, b, c;
    cout << "请输入三个整数: ";
    cin >> a >> b >> c;
    
    int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
    
    cout << "最大值是: " << max << endl;
    return 0;
}

方法 4:使用 std::max 函数

#include <iostream>
#include <algorithm> // 包含 max 函数
using namespace std;

int main() {
    int a, b, c;
    cout << "请输入三个整数: ";
    cin >> a >> b >> c;
    
    int max = std::max(a, std::max(b, c));
    
    cout << "最大值是: " << max << endl;
    return 0;
}

方法 5:使用数组和循环

#include <iostream>
using namespace std;

int main() {
    int nums[3];
    cout << "请输入三个整数: ";
    cin >> nums[0] >> nums[1] >> nums[2];
    
    int max = nums[0];
    for (int i = 1; i < 3; i++) {
        if (nums[i] > max) {
            max = nums[i];
        }
    }
    
    cout << "最大值是: " << max << endl;
    return 0;
}

方法 6:使用函数模板

#include <iostream>
using namespace std;

template <typename T>
T findMax(T a, T b, T c) {
    T max = a;
    if (b > max) max = b;
    if (c > max) max = c;
    return max;
}

int main() {
    int a, b, c;
    cout << "请输入三个整数: ";
    cin >> a >> b >> c;
    
    cout << "最大值是: " << findMax(a, b, c) << endl;
    return 0;
}

方法 7:使用指针

#include <iostream>
using namespace std;

int main() {
    int a, b, c;
    cout << "请输入三个整数: ";
    cin >> a >> b >> c;
    
    int *max = &a;
    if (b > *max) max = &b;
    if (c > *max) max = &c;
    
    cout << "最大值是: " << *max << endl;
    return 0;
}

这些方法各有优缺点,可以根据具体需求和场景选择最适合的实现方式。最简单直接的方法是使用 std::max 函数,而最通用的方法是使用函数模板。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐