#include<stdio.h>
#include <stdlib.h>
int allmonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int is_leapyear(int year)
{
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
return 1;
else return 0;
}
int days(int year, int month, int day)
{
int total = 0;
if (year < 1 || month<1 || month>12 || day<0 || day>31)
{
exit(1);
}
if ((is_leapyear(year) == 1 && month == 2 && day>29) || (is_leapyear(year) == 0 && month == 2 && day > 28))
{
exit(1);
}
for (int i = 1; i < month; i++)
{
total += allmonth[i];
}
total = total + day + is_leapyear(year);
return total;
}
void main()
{
int year, month, day;
char ch = 'y';
while (1)
{
printf("enter data\n");
scanf("%d %d %d", &year, &month, &day);
printf("%d\n", days(year, month, day));
printf("if don't continue enter n\n");
getchar();
scanf("%c", &ch);
if (ch == 'n')
break;
}
}
首先要明白的是,计算的方式不止一种,比如全局变量的数组中,存放的可以是前几个月的日期合,而不是单个日期的天数,如果改变为前几个月的日期合后,那么可以在计算的days()函数中省略一个循环结构去计算前几个月的天数,这里我只体现了最基本的方式
在这个函数中,操作都很简单,需要注意的时在使用年月日的变量值进行计算日期的时候,我们需要判断,年月日的大小是否超出范围。
其次要注意的时闰年的时候,当月数大于2月,那么我们需要在非闰年的天数答案上增加一天。
这里有一个技巧,因为我们需要计算的天数,在12而月中时随机的,所以我们需要知道12个月每个月应有的天数。我们不需要为闰年的二月进行事先赋值,因为我们只需要加一就可以完成。所以在函数的前面我们可以设置一个全局变量,作为计算天数的条件。
计算的内容需要注意的点我已经强调完了。下面我们需要注意一个语法上的内容,首先为了让这个计算功能不断的执行,而不是计算一次,打开一次程序。所以我们在main函数中,我们需要增加一个循环,来让调用的函数不断的循环执行,当我们需要结束时,他在跳出循环。
所以我使用了
while(1)
{
printf("if don't continue enter n\n");
getchar();
scanf("%c", &ch);
if (ch == 'n')
break;
}
}
这种结构来执行循环。需要注意的是,我在
printf("if don't continue enter n\n");
getchar();
C语言中清除内存缓冲区的函数是fflush( ),清除输入缓冲区用fflush(stdin); 其中stdin表示标准输入。上面的程序中getchar()的功能就是将缓存区中换行符‘\n’号清除,当然可能有些编译器不支持fflush(),这时我们可以使用getchar()
该函数通常用在输入类函数的前面,用以清除输入缓冲区中的内容,避免接收到上次残留的内容而出错。
举例如下
// 将输入的5个字符存放到数组str中,并输出
int i;
char ch, str[6]={'\0'};
for(i=0; i<5; i++)
{
scanf("%c", &ch);
str[i] = ch;
}
printf("%s\n", str);
// 程序只能输入三个字符(每个字符间包含一个回车符),因为不加fflush函数时,将残留在缓冲区中的回车符也当成了一个字符输入到数组str中。
int i;
char ch, str[6]={'\0'};
for(i=0; i<5; i++)
{
fflush(stdin); // 清除留在缓冲区中的回车符,确保接收到的是用户输入的字符
scanf("%c", &ch);
str[i] = ch;
}
printf("%s\n", str);
// 程序能正常输出
stdin标准输入,一般指键盘输入到缓冲区里的东西。