C++程序查找三个数字中最大的数

要理解本示例,您应该了解以下 C++ 编程 主题


在此程序中,用户被要求输入三个数字。

然后,此程序找出用户输入的三个数字中最大的一个,并显示出来,附带一条恰当的消息。

此程序可以有多种编写方式。


示例 1:使用 if...else 语句查找最大数

#include <iostream>
using namespace std;

int main() {
    
    double n1, n2, n3;

    cout << "Enter three numbers: ";
    cin >> n1 >> n2 >> n3;

    // check if n1 is the largest number
    if(n1 >= n2 && n1 >= n3)
        cout << "Largest number: " << n1;

    // check if n2 is the largest number
    else if(n2 >= n1 && n2 >= n3)
        cout << "Largest number: " << n2;
    
    // if neither n1 nor n2 are the largest, n3 is the largest
    else 
        cout << "Largest number: " << n3;
  
    return 0;
}

输出

Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

示例 2:使用嵌套 if...else 语句查找最大数

#include <iostream>
using namespace std;

int main() {

    double n1, n2, n3;

    cout << "Enter three numbers: ";
    cin >> n1 >> n2 >> n3;

    // check if n1 is greater than n2
    if (n1 >= n2) {

        // if n1 is also greater than n3,
        // then n1 is the largest number
        if (n1 >= n3)
            cout << "Largest number: " << n1;

        // but if n1 is less than n3
        // but n1 is greater than n2
        // then n3 is the largest number
        else
            cout << "Largest number: " << n3;
    }

     // else, n2 is greater than n1
    else {

        // if n2 is also greater than n3,
        // then n2 is the largest number
        if (n2 >= n3)
            cout << "Largest number: " << n2;

        // but if n2 is less than n3
        // but n2 is greater than n1
        // then n3 is the largest number
        else
            cout << "Largest number: " << n3;
    }

    return 0;
}

输出

Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

另请阅读

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数来查找两个数中的较大者。

  • 返回 num1 和 num2 中较大的那个数。
  • 例如,对于 num1 = 12num2 = 8,返回值应为 12。
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战