第一章 基本语法-4判断语句(if)练习平年闰年

来源:互联网 发布:nmath 非线性优化 编辑:程序博客网 时间:2024/05/17 09:23

例题:输入年月(格式如:2015 11),输出这个月的天数

分析:首先要知道平年和闰年的不同点就是闰年2月29天,平年2月28天,其他都一样

如果不用数组的话,利用if,也可以判断思路如下:


如果输入的月份是1,3,5,7,8,10,12月

     则输出  31 天

否则 如果输入的月份是  4,6,9,11月

     则输出 30 天 

否则 (也就是输入的是2月,这时需要判断平年闰年)

      如果年份是闰年

             则输出 29 天    

      否则(也就是平年)

             则输出 28 天    

按照如上思路编写程序:

#include <iostream>using namespace std;/*if语句*/int main() {int year,month;cout<<"输入年月(中间用空格隔开)"<<endl;cin>>year>>month;//如果输入的月份是1,3,5,7,8,10,12月if(month==1||month==3||month==5||month==7||month==8||month==10||month==12){   //  则输出  31 天cout<<year<<"年"<<month<<"月有31天"<<endl;}else if(month==4||month==6||month==9||month==11){//否则 如果输入的月份是  4,6,9,11月     //则输出 30 天cout<<year<<"年"<<month<<"月有30天"<<endl;}else{//否则 (也就是输入的是2月,这时需要判断平年闰年)//如果是400的倍数,或者不是100的倍数但是4的倍数 就是闰年    if(year%400==0||(year%100!=0&&year%4!=0)){//  如果年份是闰年,则输出 29 天    cout<<year<<"年"<<month<<"月有29天"<<endl;    }else{//否则(也就是平年)则输出 28 天    cout<<year<<"年"<<month<<"月有28天"<<endl;    }}return 0;}<span style="font-weight: bold;"></span>
如果使用数组来保持天数就比较简单点,

例如

int days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
用这个数组来保持平年的天数,如果是闰年的话,就把2月的天数改为29(即days[1]=29),这里要注意数组的引索是从0开始的,即第一个数是days[1],然后输出 对应月份的天数days[month-1](第month个月的天数对应数组中的第month-1个元素)。这样的话就只需要判断平年闰年,不需要判断是几月。

代码如下(数组以后文章再提):

#include <iostream>using namespace std;int main() {    int days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };    int year, month;    cout << "输入年份和月份,中间用空格隔开,例如 :2015 2" << endl;    cin >> year >> month;    /* 如果是闰年,就把2月的天数改为29,如果是平年,就把2月的天数改为28*/    if (year % 100 == 0) {        if (year % 400 == 0) {//整百的润年(400的倍数,如:2000年)            days[1] = 29;        } else {            days[1] = 28;        }    } else {//如果不是整百的年份        if (year % 4 == 0) {//普通的润年 如:2012年            days[1] = 29;        } else {            days[1] = 28;        }    }    //days[month - 1] 是month月份的天数    cout << year << "年" << month << "月,有" << days[month - 1] << "天" << endl;    return 0;}




0 0
原创粉丝点击