您的位置:首页 > 文旅 > 旅游 > 算法练习题01:月份天数

算法练习题01:月份天数

2024/10/11 9:29:12 来源:https://blog.csdn.net/2302_78946634/article/details/141614711  浏览:    关键词:算法练习题01:月份天数

【问题描述】
输入年份和月份,输出该年该月共有多少天(需要考虑闰年)
【输入格式】
输入两个整数year和month,表示年和月。
【输出格式】
一个整数,表示该年该月的天数。
【输入样例1】
1926 8
【输出样例1】
31
【输入样例2】
2000 2
【输出样例2】
29

我的答案:烂

#include<stdio.h>
int main(){int y;int m;int a1 = 29;int a2 = 28;int a3 = 30;int a4 = 31; scanf("%d",&y);scanf("%d",&m);switch(m){case 1:{printf("%d",a4);break;}case 2:{if(y%4==0&&y%100!=0||y%400==0){printf("%d",a1);}else{printf("%d",a2);}break;}case 3:{printf("%d",a4);break;}case 4:{printf("%d",a3);break;}case 5:{printf("%d",a4);break;}case 6:{printf("%d",a3);break;}case 7:{printf("%d",a4);break;}case 8:{printf("%d",a4);break;}case 9:{printf("%d",a3);break;}case 10:{printf("%d",a4);break;}case 11:{printf("%d",a3);break;}case 12:{printf("%d",a4);break;}}
} 

老师答案:

#include<iostream>
using namespace std;// 判断是否为闰年的函数
bool leap(int year) {return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}int main() {int feb, year, month;int day;cin >> year >> month;// 判断闰年,确定二月的天数if (leap(year)) {feb = 29;} else {feb = 28;}// 根据月份确定天数switch (month) {case 1: case 3: case 5: case 7: case 8: case 10: case 12:day = 31;break;case 4: case 6: case 9: case 11:day = 30;break;case 2:day = feb;break;default:cout << "Invalid month" << endl;return 1; // 返回非零值表示错误}cout << day << endl;return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com