您的位置:首页 > 其它

初识结构体

2015-06-30 16:13 281 查看
结构体的声明与使用小练习,输入今天的日期,输出明天的日期。

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

struct date {
int month;
int day;
int year;
};

int numberOfDays(struct date d);//本月最大天数
bool isLeap(struct date d);//判断是否为闰年

int main(int argc, const char * argv[]) {
// insert code here...
struct date today;
struct date tomorrow;

printf("Please enter today's date (mm dd yyyy): ");//收录今日日期
scanf("%i %i %i",&today.month,&today.day,&today.year);

if (today.day>numberOfDays(today)||today.month>12) {//判断输入时期是否合法
printf("Overflow!!!");
return 0;
}

if (today.day!=numberOfDays(today)) {//计算明天日期
tomorrow.day=today.day+1;
tomorrow.month=today.month;
tomorrow.year=today.year;
} else if(today.month==12) {
tomorrow.day=1;
tomorrow.month=1;
tomorrow.year=today.year+1;
}else{
tomorrow.day=1;
tomorrow.month=today.month+1;
tomorrow.year=today.year;
}
printf("tomorrow's date is %i-%i-%i",tomorrow.month,tomorrow.day,tomorrow.year);
return 0;
}

int numberOfDays(struct date d){
const int daysPerMonth[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int days=daysPerMonth[d.month-1];
if (d.month==2) {
if (isLeap(d)) {
days=29;
}
}
return days;
}

bool isLeap(struct date d){
bool leap=false;
if ((d.year%4==0&&d.year%100!=0)||d.year%400==0) {
leap=true;
}
return leap;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c 结构