C++ 实例 - 判断三个数中的最大数

3156 1
LZH实名认证 2022-3-17 20:18:15 | 显示全部楼层 |阅读模式
通过屏幕我们输入三个数字,并找出最大的数。

实例 - 使用 if
#include <iostream>
using namespace std;

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

    cout << "请输入三个数: ";
    cin >> n1 >> n2 >> n3;

    if(n1 >= n2 && n1 >= n3)
    {
        cout << "最大数为: " << n1;
    }

    if(n2 >= n1 && n2 >= n3)
    {
        cout << "最大数为: " << n2;
    }

    if(n3 >= n1 && n3 >= n2) {
        cout << "最大数为: " << n3;
    }

    return 0;
}
以上程序执行输出结果为:

请输入三个数: 2.3
8.3
-4.2
最大数为: 8.3
实例 - 使用 if...else
#include <iostream>
using namespace std;

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

    cout << "请输入三个数: ";
    cin >> n1 >> n2 >> n3;

    if((n1 >= n2) && (n1 >= n3))
        cout << "最大数为: " << n1;
    else if ((n2 >= n1) && (n2 >= n3))
        cout << "最大数为: " << n2;
    else
        cout << "最大数为: " << n3;
   
    return 0;
}
以上程序执行输出结果为:

请输入三个数,以空格分隔: 2.3
8.3
-4.2
最大数为: 8.3
实例 - 使用内嵌的 if...else
#include <iostream>
using namespace std;

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

    cout << "请输入三个数: ";
    cin >> n1 >> n2 >> n3;

    if (n1 >= n2)
    {
        if (n1 >= n3)
            cout << "最大数为: " << n1;
        else
            cout << "最大数为: " << n3;
    }
    else
    {
        if (n2 >= n3)
            cout << "最大数为: " << n2;
        else
            cout << "最大数为: " << n3;
    }

    return 0;
}
以上程序执行输出结果为:

请输入三个数,以空格分隔: 2.3
8.3
-4.2
最大数为: 8.3
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行