gpt4 book ai didi

c++ - 使用冒泡排序比较类对象

转载 作者:太空宇宙 更新时间:2023-11-04 13:17:21 24 4
gpt4 key购买 nike

任务:在 OOP 中为一个名为 Student 的类建模,其中包含名称、姓氏和冬季类(class)考试的分数。显示拖欠考试的学生姓名和组内前三名学生。

我在比较分数时遇到了麻烦(前三名学生)。

我的代码:

#define _CRT_SECURE_NO_WARNINGS

#include<iostream>
using namespace std;
#include <string>
#include<stdio.h>

class Student {
private:
char nume[10];
char prenume[20];
double matematica;
double fizica;
double programare;

public:
Student(char num[10], char pren[20], double mate, double fiz, double progra);
void afis();
void citire_stud();
int restanta();
double media();


};

Student::Student(char num[10] = "", char pren[20] = "", double mate = 0, double fiz = 0, double progra = 0)
{
strcpy(nume, num);
strcpy(prenume, pren);
matematica = mate;
fizica = fiz;
programare = progra;
}


void Student::afis()
{
cout << "Nume: " << nume << endl;
cout << "Prenume: " << prenume << endl;
cout << "Nota la matematica: " << matematica << endl;
cout << "Nota fizica: " << fizica << endl;
cout << "Nota programare: " << programare << endl;
cout << endl;

}

void Student::citire_stud()
{
char num[10];
char pren[20];
double mate, fiz, progra;

cout << "Introduceti numele studentului: " << endl;
cin >> num;
strcpy(nume, num);

cout << "Introduceti preumele studentului: " << endl;
cin >> pren;
strcpy(prenume, pren);

cout << "Introduceti nota la mate studentului: " << endl;
cin >> mate;
matematica = mate;

cout << "Introduceti nota la fizica studentului: " << endl;
cin >> fiz;
fizica = fiz;

cout << "Introduceti nota la programare studentului: " << endl;
cin >> progra;
programare = progra;

}

int Student::restanta() //arrears
{
if (matematica < 5 || programare <5 || fizica < 5)
return 1;
else return 0;
}

double Student::media()
{
double med;
med = (matematica + fizica + programare) / 3;
return med;

}

void main()
{
int cont = 0;
int res[10];
int nr;

cout << "Cati studenti sunt(max 10): "; //How many students
cin >> nr;

Student ob2[10], temp;
for (int i = 0;i < nr;i++)
{
ob2[i].citire_stud();
if (ob2[i].restanta())
{

res[cont++] = i;
}

}
if (cont == 0)
{
cout << "Nu sunt studenti restanti! " << endl;
goto jmp;
}
else
{
cout << "\nStundetii restanti sunt: " << endl;
int i = 0;
int k = 0;
do
{
k = res[i];
ob2[k].afis();
i++;

} while (i != cont);
}

jmp:
cout << "\n\n\n\nStudentii in ordinea medilor sunt: " << endl;

for (int i = 0;i < nr;i++)
{

if (ob2[i].media() < ob2[i + 1].media()) //Not working
{
temp = ob2[i];
ob2[i] = ob2[i + 1];
ob2[i + 1] = temp;



}
}
for (int i = 0;i < nr;i++)
ob2[i].afis();


system("pause");

}

输出:Output

应该是:9 - 7 - 5

最佳答案

你的冒泡排序坏了。 A) 你需要 2 个循环。 B) 你出界了。将其更改为:

for (int j = 0; j < nr; j++)
{
for (int i = 0;i < nr - 1 ; i++)
{

if (ob2[i].media() < ob2[i + 1].media())
{
temp = ob2[i];
ob2[i] = ob2[i + 1];
ob2[i + 1] = temp;
}
}
}

关于c++ - 使用冒泡排序比较类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36715840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com