code show as below
//输入年月日求是该年的第几天?并判断闰年,若是闰年返回1,不是则返回0
#include <stdio.h>
int LeapYear(int year);//判断是不是闰年的函数。函数原型声明
int main()
{
int year,month,day;
printf("请输入日期:\n");
while(1) //控制用户输入格式,输入的 月份和天数 正确才可继续,否则需要重新输入
{
scanf("%d,%d,%d",&year,&month,&day);
if(month<1 || month>12 || day<1 || day>31)
printf("输入日期错误!请您重新输入!\n");
else
break; //若正确,则跳出while循环,继续执行下面步骤
}
//下面数组中的0值得思考。
//可以这么想,如果用户输入2020,1,15。(假设用户输入正确)
//那么由于是1月份,所以用户输入的第三个数字 是 几 就是第几天
int array[]={
0,28,31,30,31,30,31,31,30,31,30,31};
int sum=0; //sum即为该年的"第多少天"
if(month==1)
sum=day;
else if(month==2)//若是2月份,"第多少天"应该再加上前边1月份的天数
sum=day+31;
else{
//若既不是1月份,也不是2月份,那么开始求是"第多少天"
for(int i=0;i<month;i++)
sum+=array[i];//比如:2018,3,23。那么即:array[0]+array[1]+array[2]=0+28+31。还应再 +23。最后=第82天
sum+=day;//因为下标是从0开始的,故应再添加上输入的天数(日子)
if(LeapYear(year)) //若是闰年,算出来的天数应该再加上1
sum++;
}
printf("该日期是第%d天\n",sum);
return 0;
}
int LeapYear(int year)
{
if((year%4==0 && year%100!=0) || (year%400==0))
{
return 1;
}
else
return 0;
}
test
The code analysis is actually written very clearly in the comments!
Below are a few test inputs and their output results.
This example is what I wrote in the comments:
2018 is not a leap year, so +1 is not needed.
Here's another example of testing leap years:
Obviously, compared to the previous result, in this test, since 2020 is a leap year, when a day in March is the day of the year, February has 29 days, so the final result should be 82 +1=83.
Next, test the prompt of the user error output:
Here's what happens when the months entered don't match:
Try again with a different month and year:
Here's what happens when the number of days is wrong:
Because only the changed output statement, no longer put all the code, there are ah!
printf("输入日期错误!请您重新输入:\n");
printf("该日期是%d年的第%d天\n",year,sum);
A few tests:
—————————————————————————————————
There is a small bug, I wonder if you found it:
...So, it is also a "pot" for input judgment, haha! I'll leave it to the reader to improve it! ! !