任务:在OOP中建模一个名为Student的类,该类包含名称、姓氏和冬季考试的分数。显示欠费考试的学生和组中前三名学生的姓名。
我很难比较分数(前三名学生)。
我的代码:
#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 << "nnnnStudentii 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");
}
输出:输出
应该是:9-7-5
您的冒泡排序已被破坏。A) 你需要两个循环。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;
}
}
}