目录
前言:
开新专栏了,讲解100道基础语法编程题
用c语言讲解
目的是复习c语言中的基础语法,为单片机中的c语言代码分析做铺垫
专栏链接:
1、题目展示:
2、问题分析:
首先解决输入问题
需要输入数据有多组,每组占一行,数据格式是XXXX年/XX月/XX日
输入多组数据我们已经很熟练了,详情请见01、ASCII码排序
关键在于XXXX年/XX月/XX日中的斜杠怎么办
其实scanf就可以解决,但是注意为了使输入三个整数还有斜杠时(也就是XXXX/XX/XX)scanf返回值为3,占位符要这样处理
接下来解决核心问题
怎么确定任意一年任意一个月的某一天在一年当中是第几天
首先对于平年,比如3月20日,先把3月份之前的1月和2月有几天加上,再把day=20加上
day=20加上很容易,
关键是怎么把任意一个月之前的月份有几天都算出来
利用循环和数组和函数
首先定义一个函数用于计算任意一个月之前的月份有几天,具体内容如下
现在我们来解决闰年的问题
1、闰年是年份能被4整除并且不能被100整除或者能被400整除
2、闰年比平年多一天
3、如果是闰年,但是月份是<=2月,这个月之前的月份总天数依然和平年一样,如果月份是>=2月,那么这个月之前的月份总天数要在上面函数的基础上加1天,因为闰年2月多了一天
方法2:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int is_leap_year(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}//年份是否是闰年的判断函数
int calculate_day_of_year(int year, int month, int day) {
int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//把第1个元素设成0,下面i就从1开始
int total_days = day;
// 累加前 month-1 个月的天数
for (int i = 1; i < month; i++) {
total_days += days_in_month[i];
}
// 闰年且月份超过2月时,加1天
if (is_leap_year(year) && month > 2) {
total_days += 1;
}
return total_days;
}
int main() {
int year, month, day;
while (scanf("%d/%d/%d", &year, &month, &day) ==3) {
printf("%d\n", calculate_day_of_year(year, month, day));
}
return 0;
}
3、法1最终代码展示:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int total_days(int month) {
int day_of_month[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
int sum_days = 0;
for (int i = 0;i < month - 1;++i) {
sum_days += day_of_month[i];
}
return sum_days;
}
int main() {
int year, month, day;
while (scanf("%d/%d/%d", &year, &month, &day) ==3) {
int is_leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
int finally_days = total_days(month) + day;
if (is_leap && month > 2) {
finally_days = finally_days + 1;
}
printf("%d\n", finally_days);
}
return 0;
}