输入年月日,计算这一天是这一年的第几天
结构体定义
typedef struct Date
{
int Year;
int Month;
int Day;
}Date;
求总共天数的函数实现
int All_Days(Date* pdate)
{
assert(pdate != nullptr);
int i = 0, sum = 0, num = 0;
for (i = 1; i < pdate->Month; ++i)
{
switch (i)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
num = 31;
break;
case 4:
case 6:
case 9:
case 11:
num = 30;
break;
default:
{
if (Is_Leap_Year(pdate))
{
num = 29;
}
else
{
num = 28;
}
break;
}
}
sum += num;
}
return (sum += pdate->Day);
}
这里进行求和的方法多种多样,也可以把每个月的天数写成数组形式来进行访问。
判断是否为闰年
bool Is_Leap_Year(Date* pdate)
{
return ((pdate->Year % 4 == 0 && pdate->Year % 100 != 0) || (pdate->Year % 400 == 0));
}
输入示例
主函数
int main(void)
{
Date date;
int days = 0;
printf("Please input year, month and day:\n");
scanf_s("%d %d %d", &date.Year, &date.Month, &date.Day);
days = All_Days(&date);
printf("This day is the Day %3d.\n", days);
return 0;
}
运行结果:
平年结果
闰年结果
打印一个学生的成绩数组
结构体定义
typedef struct Student
{
int num;
char name[20];
float score[3];
}Student;
输入函数
void Input(Student* pstud)
{
assert(pstud != nullptr);
int i = 0, j = 0;
Student* p = pstud;
for (i = 0; i < 5; ++i)
{
printf("Please input NO.%d student information:\n", i + 1);
printf("Num: ");
scanf_s("%d", &p[i].num);
printf("Name: ");
scanf_s("%s", p[i].name, 20);
printf("Score: ");
for (j = 0; j < 3; ++j)
scanf_s("%f", &p[i].score[j]);
printf("\n");
}
printf("\n");
}
输出函数
void Print(Student* pstud)
{
assert(pstud != nullptr);
int i = 0, j = 0;
Student* p = pstud;
for (printf("Print Result:\n\n"), i = 0; i < 5; ++i)
{
printf("Num :%3d\n", p[i].num);
printf("Name : %-10s\n", p[i].name, 20);
for (j = 0; j < 3; ++j)
{
printf("Score%d:%5.2f\n", i + 1, p[i].score[j]);
}
printf("\n");
}
}
输出示例
主函数
int main(void)
{
Student Stud[5];
Input(Stud);
Print(Stud);
printf("\tProgram Exit!\n");
return 0;
}
运行结果
输入
输出
Print Result:
Num : 1
Name : Srh
Score1:100.00
Score1:99.00
Score1:86.00
Num : 2
Name : zzc
Score2:87.00
Score2:96.00
Score2:100.00
Num : 3
Name : sauron
Score3:100.00
Score3:90.00
Score3:75.00
Num : 4
Name : adfee
Score4:77.00
Score4:96.00
Score4:85.00
Num : 5
Name : liu
Score5:100.00
Score5:100.00
Score5:100.00
Program Exit!