C++第二章部分例题

发布时间 2023-04-10 22:38:15作者: 信工薛晨昊

例2-1

“Hello Welcome to C++”

代码部分:

#include<iostream>
using namespace std;
int main()
{
cout << "hello!" << endl;
cout << "Welcome to C++!" << endl;
return 0;
}

 

例2-2

输入一个年份,判断是否闰年

分析部分:

闰年可以被4整除不能被100整除,或能被400整除。 

代码部分:

#include<iostream>
using namespace std;
int main()
{
int year;
bool isLeapYear;
cout << "Enter the year:";
cin >> year;
isLeapYear = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
if (isLeapYear)
cout << year << " is a Leap year" << endl;
else
cout << year << " is not a leap year" << endl;
return 0;
}

 

例2-3

比较两个数的大小

分析:两个数比较有三种可能大于,小于,等于。

代码部分:

#include<iostream>
using namespace std;
int main()
{
    int x, y;
    cout << "Enter x and y:";
    cin >> x >> y;
    if (x = y)
    {
        cout << "x=y" << endl;
    }
    else
    {
        if (x > y)
            cout << "x>y" << endl;
        else
            cout << "x<y" << endl;
    }
    return 0;
}