C++ | 结构体 | 实验八

项目一

 定义一个结构体变量(包括年、月、日),编写程序,要求输入年月日,程序能计算出该日在本年中第几天。注意闰年问题。  


#include <iostream>
using namespace std;
struct time
{
	int years;
	int months;
	int days;
}date;

int main()
{
	int day = 0, i;
	int a[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	cout << "输入准确日期:" << endl;
	cin >> date.years >> date.months >> date.days;
	for (i = 0; i<date.months; i++)
	{
		day = day + a[i];
	}
	day = day + date.days;
	if ((((date.years % 4 == 0) && (date.years % 100 != 0))
		|| (date.years % 400 == 0)) && date.months >= 3)
	{
		day = day + 1;
	}
	if (date.months > 12 || (date.months == 2 && date.days > 28) || (((date.years % 4 == 0) && (date.years % 100 != 0))
		|| (date.years % 400 == 0)) && date.months == 2&&date.days>29 || date.days > 31)
		//本语句严格限定了可能的范围外情况
	{
		cout << "超出范围,请重新输入!" << endl;
	}
	else
	{
		cout << date.months << "月" << date.days << "日是"
			<< date.years << "年中的第" << day << "天" << endl;
	}
	system("pause");
	return 0;
}
项目2

 5个学生,每个学生的数据包括学号、班级、姓名、3门课程。从键盘输入5个学生数据,要求打印出每个学生3门课程的平均成绩,以及平均分最高的学生数据(包括学号、班级、姓名、3门课程、平均分)。要求:

1.定义学生结构体类型及大小为5的该结构体数组。

2.用一个函数实现5个学生数据的输入,用另一个函数负责求每个学生3门课程的平均成绩,再用一个函数求出平均分最高的学生,并输出该学生的数据。

3.平均分和平均分最高的学生数据都在主函数中输出。


#include<iostream>
using namespace std;

struct student
{
	int ID;
	int Class;
	char Name[20];
	int English;
	int Math;
	int Chinese;
	float Average;
};

void putIn(student*stu, int n)
{
	cout << "请输入学生ID,班级,名字,三科成绩 " << endl;
	for (int i = 0; i < n; i++)
	{
		cout << "请输入第" << i+1 << "个学生信息" << endl;
		cin >> stu[i].ID >> stu[i].Class >> stu[i].Name >> stu[i].English >> stu[i].Math >> stu[i].Chinese;
	}
}

void Average(student*stu,int n)
{
	for (int i = 0; i < n; i++)
	{
		stu[i].Average = (stu[i].English + stu[i].Math + stu[i].Chinese) / (float)3;
	}
}


void Max(student* stu, int n, student* *max)
{
	*max = &stu[0];
	for (int i = 0; i < 5; i++)
	{
		if ((*max)->Average < stu[i].Average)
		{
			*max = &stu[i];
		}
	}
}
int main()
{
	int m;
	student stu[5];
	student* buf=NULL;
	putIn(stu, 5);
	system("cls");
	Average (stu, 5);
	cout << "姓名" << ' ' << "平均成绩" << endl;
	for (int i = 0; i < 5; i++)
	{
		cout << stu[i].Name << ' ' << stu[i].Average<<endl;
	}
	Max(stu, 5, &buf);
	cout << "最高分学生信息 " << endl;
	cout << "ID" << '\t' << "班级" << '\t'  << "姓名" << '\t'  << "英" << '\t' << "数学" << '\t' << "语文" << '\t' << "平均成绩" << endl;
	cout << buf->ID << '\t' << buf->Class << '\t' << buf->Name <<  '\t' << buf->English << '\t' << buf->Math <<  '\t' 
		<< buf->Chinese <<  '\t'  << buf->Average<< endl;
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/IronBull_Zhang/article/details/80872690