哈喽大家好,我是保护小周ღ,本期为大家带来的是编程实现输入某年某月某日,输出它是这一年的第几天,一起来看看把~

多组输入,编程实现输入某年某月某日,输出它是这一年的第几天。
(注意数据输入范围)
2021-5-1
It is not a leap year.
Today is the 121 day of the year.
2000-5-1
It is a leap year.
Today is the 122 day of the year.
2020-13-12
Input error, please re-enter the date.
首先我们输入一个日期,我们可以定义三个变量year,month,day,代表年月日,也可以用结构体描述一个日期。利用switch(month)函数判断该年月日有多少天,输入年份,如果该年是闰年,那么该年的2月有29天,否则2月只有28天。
一个月有31天的月份有1 3 5 7 8 10 12
一个月有30天的月份有4 6 9 11
闰年的判断条件,年份能被4整除且不能被100整除,但是能够被400整除的才算闰年。
题目还涉及到多组输入,这个问题我们就要了解一下scanf()函数;scanf()是针对标准输入流的格式化输入函数。
怎样实现多组输入呢? scanf() 函数是有返回值的,scanf()的返回值是已经成功赋值的变量个数,且为整型。
例如:
int size=scanf("%d %d",&a,&b);
键盘输入1 2时scanf()的返回值就是2,所以size==2;
如果只有a或b其中一个被成功读入,那么scanf()的返回值为1;
如果只有a和b 都未被成功读入,返回值为0;
另外还有一种写法是多组输入的写法是要用到EOF,EOF 是 end of file的缩写,表示“文字流”的结尾(file),也可以是标准输入的结尾(stdin)。
例如:
int size=scanf("%d %d",&a,&b);
如果 遇到错误或者是遇到了end of file 返回值就为EOF。
所以我们多组输入可以这样写:
- while(scanf("%d %d",&a,&b)==2)
- {
- ……
- }
还可以这样写:
- while(scanf("%d %d",&a,&b)!=EOF)
- {
- ……
- }
- #include<stdio.h>、
-
- //判断是否闰年,若是闰年则返回1,若不是闰年则返回0
- int IfLeapYear(int year)
- {
- if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
- return 1;
- else
- return 0;
- }
-
- //Days函数:判断有多少天
- Days(int year, int month, int day)
- {
- int d, days = 0;
- //判断是否闰年
- int size = IfLeapYear(year);
- if (size == 0)
- {
- printf("It is not a leap year.\n");
- }
- else
- {
- printf("It is a leap year.\n");
- }
- //遍历已经完整过去的月份,并统计每个满月的天数
- for (int i = 1; i < month; i++)
- {
- switch (i)
- {
- case 2:
- if(size==1)
- {
- d = 29;
- }
- else
- {
- d = 28;
- }break;
- case 1:
- case 3:
- case 5:
- case 7:
- case 8:
- case 10:
- case 12:d = 31; break;
- case 4:
- case 6:
- case 9:
- case 11:d = 30; break;
- default:printf("error\n");
- }
- days += d;
- }
- //统计“残月”的天数
- days += day;
- return days;//返回总天数
- }
-
- int main()
- {
- int year, month, day;
- printf("请输入一个日期,判断他是一年的那一天。\n");
- while (scanf("%d-%d-%d", &year, &month, &day)==3)//scanf("%d-%d-%d", &year, &month, &day)!=EOF
- {
- //判断月份是否输入正确
- if (month < 1 || month>12)
- {
- printf("Input error, please re-enter the date:\n");
- }
- else
- printf("Today is the %d day of the year.\n",Days(year, month, day));
- }
- return 0;
- }

- //定义日期类型
- typedef struct Date
- {
- int year;
- int month;
- int day;
-
- }Date;
-
- int main()
- {
- //定义日期类型的Date1变量
- Date Date1;
- printf("请输入一个日期,判断他是一年的那一天。\n");
- while (scanf("%d-%d-%d", &Date1.year, &Date1.month, &Date1.day) == 3)//scanf("%d-%d-%d", &year, &month, &day)!=EOF
- {
- if (Date1.month < 1 || Date1.month>12)
- {
- printf("Input error, please re-enter the date:\n");
- }
- else
- //这样我们就可以把Date类型的Date1变量作为一个整体传参,如果传地址就可以用Date* 的指针接收,通过指针访问Date1的各个成员
- printf("Today is the %d day of the year.\n", Days(&Date1);
- }
- return 0;
- }
在结构体方面有什么不懂得,可以参考博主的另一篇博客,详细的介绍了
1.结构体类型的声明
感兴趣的朋友可以用博主的方法,或者是自己的方法做做这道题,优化一下代码,尝试怎样判断我们在正确输入月份后,输入的天数在正确的范围内呢?欢迎评论区留言。
分享一个牛客网上类似的题目,大家也可以尝试着做一做。
感谢每一个观看本篇文章的朋友,更多精彩敬请期待:保护小周ღ *★,°*:.☆( ̄▽ ̄)/$:*.°★*

如有侵权请联系修改删除!