你之前写的代码有问题,没有按照题目要求来。
所以我重新写了一份,你看看是你需要的吧。(如果有不懂的尽管问 :))
如果对你有帮助,点个采纳可否 QAQ~
这是代码:
#include <iostream>
#include <fstream>
struct Student
{
int id;
char name[20];
double math, phy, chem;
double ave, total;
};
void average(Student* const stu, uint32_t size)
{
for(int i = 0; i < size; i++)
{
stu[i].total = stu[i].math + stu[i].phy + stu[i].chem;
stu[i].ave = stu[i].total / 3;
}
}
void sort(Student* const stu, uint32_t size)
{
// lambda function for swapping
auto swap = [](Student* lhs, Student* rhs) -> void {
Student temp = *rhs;
*rhs = *lhs;
*lhs = temp;
};
// simple bubble sort
for(int i = size - 1; i > 0; i--)
{
for(int j = 0; j < i; j++)
{
if(stu[j].total < stu[j + 1].total)
swap(&stu[j], &stu[j + 1]);
}
}
}
void write2file(const std::string& path, const Student* const stu, uint32_t size)
{
std::ofstream fout;
fout.open(path, std::ios::out);
// if path file does not exist, one will be created
for(int i = 0; i < size; i++)
{
fout << stu[i].id << ' ' << stu[i].name << ' '
<< stu[i].math << ' ' << stu[i].phy << ' ' << stu[i].chem << ' '
<< stu[i].ave << ' ' << stu[i].total << '\n';
}
}
#define TEST
#ifdef TEST
int main()
{
// array contain three students
Student arr[3] = {
{1, "tom", 90, 78, 67},
{2, "lily", 100, 87, 98},
{3, "abby", 97, 60, 79}
};
average(arr, 3);
sort(arr, 3);
write2file("test.txt", arr, 3);
}
#endif
这是输出文档:
2 lily 100 87 98 95 285
3 abby 97 60 79 78.6667 236
1 tom 90 78 67 78.3333 235