1,2,3
//Date.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
typedef struct {
int year;
int month;
int day;
}Date;
const int NoLeapYear[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
int LeapYear(int y) {
return(y % 4 == 0 && y % 100 != 0) || (y % 400) == 0;
}
int DateToNum(Date dt) {
int i;
int ndays = 0;
for (i = 1; i < dt.year; i++)
ndays += LeapYear(i) ? 366 : 365;
for (i = 1; i < dt.month; i++)
ndays += NoLeapYear[i - 1];
if (dt.month > 2 && LeapYear(dt.year))
ndays++;
ndays += dt.day;
return ndays;
}
Date NumToDate(int ndays) {
Date dt = { 0,0,0 };
unsigned n;
if (ndays <= 0) {
printf("NumToDate: ndays illegal!\n");
exit(1);
}
dt.year = 1;
n = 365;
while (ndays > n) {
ndays -= n;
dt.year++;
n = LeapYear(dt.year) ? 366 : 365;
}
dt.month = 1;
n = 31;
while (ndays > n) {
ndays -= n;
dt.month++;
n = NoLeapYear[dt.month - 1];
if (dt.month == 2 && LeapYear(dt.year))
n++;
}
dt.day = ndays;
return dt;
}
//main.c
#include"Date.h"
#include<stdio.h>
int main() {
printf("计算一个日期加上和减去一个数字所得到的日期:\n");
printf("输入一个日期(年,月,日)和一个数字:\n");
Date dt;
int num;
Date temp_d;
int temp_n;
scanf_s("%d%d%d%d", &dt.year, &dt.month, &dt.day, &num);
temp_n = DateToNum(dt) - num;
temp_d = NumToDate(temp_n);
printf("减去值的日期:%d年%d月%d日\n", temp_d.year, temp_d.month, temp_d.day);
temp_n = DateToNum(dt) + num;
temp_d = NumToDate(temp_n);
printf("加上值的日期:%d年%d月%d日\n", temp_d.year, temp_d.month, temp_d.day);
Date dt2 = { 2010,1,1 };
printf("输入一个日期以判断当天打鱼还是晒网(2011年以后):");
Date dt3;
int temp1, temp2, temp3;
scanf_s("%d%d%d", &dt3.year, &dt3.month, &dt3.day);
temp1 = DateToNum(dt2);
temp2 = DateToNum(dt3);
temp3 = temp2 - temp1;
if (temp3 % 5 == 3 || temp3 % 5 == 4)
printf("晒网");
else
printf("打鱼");
return 0;
}
4
//main.c
#include<stdio.h>
typedef struct {
int id;
double score;
}Student;
int IndexOfMax(const Student* p, int n);
void Selection_s(Student* p, int n);
void SwapByAddress(Student* p, int a, int b);
void OutputArray(const Student* p, int n);
int main() {
Student s[10];
int i;
printf("请输入十个学生的学号(两位数)和平均成绩:\n");
for (i = 0; i < 10; i++)
scanf_s("%d%lf", &(s[i].id), &(s[i].score));
//对于scanf函数,double输入使用%lf,float输入使用%f
//只有printf才可以使用%f输出double和float,因为有自动类型提升
Selection_s(s, 10);
OutputArray(s, 10);
return 0;
}
int IndexOfMax(const Student* p, int n) {
int i;
int max = 0;
for (i = 1; i < n; i++) {
if (p[max].score < p[i].score)
max = i;
}
return max;
}
void Selection_s(Student* p, int n) {
int max;
while (n > 1) {
max = IndexOfMax(p, n);
SwapByAddress(p, max, n - 1);
n--;
}
}
void SwapByAddress(Student* p, int a, int b) {
Student temp;
temp = p[a];
p[a] = p[b];
p[b] = temp;
}
void OutputArray(const Student* p, int n) {
int i;
for (i = 0; i < n; i++)
{
printf("%d\t%f", p[i].id, p[i].score);
printf("\n");
}
}