C++ 實例 - 判斷三個數中的最大數
通過螢幕我們輸入三個數字,並找出最大的數。
實例 - 使用 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

 C++ 實例