C语言作业(三)
Wucheng

一点小记录

大一上学期学到指针与结构体,下个学期就是痛苦的数据结构
指针的最基本运用还是比较简单的无非就是*&
结构体也比较易懂,联合指针与数组在程序中存读据方便了很多
联和前面所学的东西对于初学者最大的难点貌似还是理解问题,暂时还不涉及到复杂的算法


指针输出结构体

利用指针输出一年月份的天数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<stdio.h>
struct mon_day
{
char month[10];
int day;
};

struct mon_day mon[12] = {{"January",31},{"February",28},{"March",31},{"April",30},
{"May",31},{"June",30,},{"July",31},{"August",31},{"September",30},
{"October",31},{"November",30},{"December",31}};

int main(void)
{
struct mon_day *p;

for ( p = mon; p < mon+12; p++)
{
printf("%-10s have %-2d days.\n",p -> month,p -> day);
//结构体数组在内存地址的排列是按顺序的,只需要调用指针指向下一个内存地址即可
//要调用结构体内的数据必须要指向运算符"->"
}
}

输出天数

输入一个日期,并且输出这天是今年的多少天

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<stdio.h>
struct date
{
int year;
int month;
int day;
};

int main()
{
struct date today;
struct date *p = &today;

printf("Please Enter date:");
scanf("%d/%d/%d",&p -> year,&p -> month,&p -> day);

printf("Today is the %d day",when(today));
}

int when (struct date d)
{
int month[12] = {31,28,31,30,31,30,31,31,30,31,30,31};//每个月份的天数
int days = 0;

if(leap(d.year)) month[1] = 29;//调用自定义函数leap传入d.year数值判断是否闰年

for (size_t i = 0; i < d.month - 1; i++)
{
days += month[i];
}

days += d.day;
return days;
}

int leap(int year)//判断闰年
{
if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0) return 1;
else return 0;
}