C语言 第十一章

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第十一章结构体与共同体

1.定义一个结构体变量(包括年、月、日)。计算该日在本年中是第几天?注意润年问题。

解法一:

结构体变量中的成员对应于输入的年月日。Days为天数。

Struct

{int year;

int month;

int day;

}date;

main()

{int days;

printf(“Input year,month,day:”);

scanf(“%d,%d,%d”,&date.year,&date.month,&date.day);

swith(date.month)

{ case 1: days=date.day; break;

case 2: days=date.day+31; break;

case 3: days=date.day+59; break;

case 4: days=date.day+90; break;

case 5: days=date.day+120; break;

case 6: days=date.day+151; break;

case 7: days=date.day+181; break;

case 8: days=date.day+212; break;

case 9: days=date.day+243; break;

case 10: days=date.day+273; break;

case 11: days=date.day+304; break;

case 12: days=date.day+334; break;

}

if ( (date.year %4= = 0 && date.year % 100 ! =0

‖date.year %4= = 0 )&&date.month>=3)days+ = 1;

printf(“\n%d/%d is the %th day in%d.”,date.month.date.day,days, date.year );

}

解法二:

struct date

{int year;

int month;

int day;

}

main()

{int i,days

int day_tab[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};

printf (“Input year ,month,day:”);

scanf(“%d,%d,%d”,&date.year,%date.month,&date.day);

days = 0;

for (i=1;i

days+ =day_tab[i];

days + =date.day;

if((date.year%4= = 0 & & date.year%100! = 0‖date.year%400= =0) & & date.

month>=3)

days+ =1;

printf(“%d/%d is the %dth day in %d.”,date.month,date,day,date.year); }

2.写一个函数days,实现上面的计算。由主函数将年月日传递给days 函数,计算后将日数传回主函数输出。

解:

struct y_m_d

{int year;

int month;

int day;

}date;

intdays(struct y_m_d date 1)

{int sum;

switch(datw1.month)

{case1:sum = date1.day; break;

case2:sum = date1.day+31; break;

case3:sum = date1.day+59; break;

case4:sum = date1.day+90; break;

case5:sum = date1.day+120; break;

case6:sum = date1.day+151; break;

case7:sum = date1.day+181; break;

case8:sum = date1.day+212; break;

case9:sum = date1.day+243; break;

case10:sum = date1.day+273; break;

case11:sum = date1.day+304; break;

case12:sum = date1.day+334; break;

}

if((date1.year % 4 = = 0 && date.year % 100! =0

‖date1.year% 400 = = 0)&& date1.month>=3)

sum+=1;

return(sum);

}

main()

{printf(“Input year ,month,day:”)

scanf(“%d,%d,%d”,&date.year,%date.month,&date.day);

printf(“\n”);

printf(“%d / %d is the %dth day

相关文档
最新文档