c++实例,超实用,【初学者速看收藏】

726 阅读1分钟

判断三个数中的最大数

#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;
}

判断闰年

#include <iostream>
using namespace std;
 
int main()
{
    int year;
 
    cout << "输入年份: ";
    cin >> year;
 
    if (year % 4 == 0)
    {
        if (year % 100 == 0)
        {
            // // 这里如果被 400 整除是闰年
            if (year % 400 == 0)
                cout << year << " 是闰年";
            else
                cout << year << " 不是闰年";
        }
        else
            cout << year << " 是闰年";
    }
    else
        cout << year << " 不是闰年";
 
    return 0;
}

求两数的最大公约数

#include <iostream>
using namespace std;
 
int main()
{
    int n1, n2;
 
    cout << "输入两个整数: ";
    cin >> n1 >> n2;
    
    while(n1 != n2)
    {
        if(n1 > n2)
            n1 -= n2;
        else
            n2 -= n1;
    }
 
    cout << "HCF = " << n1;
    return 0;
}

求两数最小公倍数

#include <iostream>
using namespace std;
 
int main()
{
    int n1, n2, max;
 
    cout << "输入两个数: ";
    cin >> n1 >> n2;
    
    // 获取最大的数
    max = (n1 > n2) ? n1 : n2;
 
    do
    {
        if (max % n1 == 0 && max % n2 == 0)
        {
            cout << "LCM = " << max;
            break;
        }
        else
            ++max;
    } while (true);
    
    return 0;
}

求一个数的阶乘

#include <iostream>
using namespace std;
 
int main()
{
    unsigned int n;
    unsigned long long factorial = 1;
 
    cout << "输入一个整数: ";
    cin >> n;
 
    for(int i = 1; i <=n; ++i)
    {
        factorial *= i;
    }
 
    cout << n << " 的阶乘为:"<< " = " << factorial;    
    return 0;
}

实现一个简单的计算器
。。。

完全代码,请移步到公众号:诗一样的代码

在这里插入图片描述