今天看到一道练习题觉得有必要记录以下。接下来我们看一下题目要求:
编写函数,求昨天的日期。并在主函数中调用它。
如果我们在这里使用C语言标准库 里面的 <time.h>可以直接获取当前计算机时间然后只需要减去一天的时间就可以了代码如下:
#include <stdio.h>
#include <time.h>
int times(){
time_t st = time(NULL) -24*60*60;
struct tm *t=localtime(&st);
printf("%d年%d月%d日\n",1900+t->tm_year,t->tm_mon+1,t->tm_mday);
return 0;
}
int main(){
times();
return 0;
}
那么如果我们不使用<time.h>库该怎么实现呢?
分析:
- 我们判断当前日期是不是1将日期减1
- 如果是1那么我们要根据当前月份来更改并将月份减1(当减去后的1为0时将月份修改为12)
- 如果月份是2、4、6、8、9、11、1月将日期改为31日
- 如果月份是5、7、10、12月将日期改为30日
- 如果是2月那么判断是否为闰年
- 如果是闰年将日期改为29
- 如果是平年将日期改为28.
- 如果是1月1日那么将年份改为前一年。
我们来看一下我写的代码:
#include <stdio.h>
int times(int year,int mouths,int day){
//判断月份和日期是否合法
int bool = 1;
if(mouths>0&&mouths<=12){
if(mouths==1||mouths==3||mouths==5||mouths==7||mouths==8||mouths==10||mouths==12){
if(day<=0||day>31){
bool = 0;
printf("输入的日期是非法日期!");
}
}
else if(mouths==4||mouths==6||mouths==9||mouths==11){
if(day<=0||day>30){
bool = 0;
printf("输入的日期是非法日期!");
}
}
else if(mouths==2){
if(year%4==0&&year%100!=0||year%100==0){
if(day<=0||day>29){
bool = 0;
printf("输入的日期是非法日期!");
}
}
else{
if(day<=0||day>28){
bool = 0;
printf("输入的日期是非法日期!");
}
}
}
}
//计算日期
if(bool==1){
if(mouths==1&&day==1){
year = year-1;
}
if(day == 1){
if(mouths==1||mouths==2||mouths==4||mouths==6||mouths==8||mouths==9||mouths==11){
day=31;
mouths=mouths-1;
}
else if(mouths==5||mouths==7||mouths==10||mouths==12){
day=30;
mouths=mouths-1;
}
else if(mouths==3){
if(year%4==0&&year%100!=0||year%100==0){
day = 29;
mouths=mouths-1;
}
else{
day=28;
mouths=mouths-1;
}
}
}
else{
day=day-1;
}
if(mouths==0){
mouths=12;
}
printf("%d年%d月%d日\n",year,mouths,day);
}
}
int main(){
int year,mouths,day;
printf("请输入年月日");
scanf("%d %d %d",&year,&mouths,&day) ;
times(year,mouths,day);
return 0;
}