C++高手帮个忙啊!!!很急!!!这个程序老编译时总是出一个错误,我不知道为什么会错,高手帮忙啊!!!

2024年12月04日 04:41
有3个网友回答
网友(1):

什么错误?

我汗,直接using namespace std;不久不用写那么多的using std::。。。

网友(2):

你先算算你头文件用了几个,还有啊,你那命名空间是搞了玩啊,这不是给你玩游戏

网友(3):

#include
#include
#include
#include
#include
#include
#include

using std::cin;
using std::cout;
using std::endl;
using std::setprecision;
using std::sort;
using std::streamsize;
using std::string;
using std::vector;
using std::domain_error;
using std::max;
using std::istream;
using std::setw;

struct Student_info {
string name;
double midterm, final;
vector homework;
};

bool compare(const Student_info& x, const Student_info& y)
{
return x.name < y.name;
}

istream& read_hw(istream& in, vector& hw)
{
if (in){
hw.clear();

double x;
while (in >> x){
hw.push_back(x);
}
in.clear();
}

return in;
}

istream& read(istream& is, Student_info& s)
{
is >> s.name >> s.midterm >> s.final;
read_hw(is, s.homework);
return is;
}

double median(vector vec)
{
typedef vector::size_type vec_sz;

vec_sz size = vec.size();

if (size == 0)
throw domain_error("median of an empty vector");

sort(vec.begin(), vec.end());

vec_sz mid = size / 2;

return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 :vec[mid];
}

double grade(Student_info& s)
{
return 0.2 * s.midterm + 0.4 * s.final + 0.4 * median(s.homework);//这里原本的0.4*s.homework是错误的,原因是homework是vector类型..没办法乘积
}

int main()
{
vector students;
Student_info record;
string::size_type maxlen = 0;

while (read(cin, record)){
maxlen = max(maxlen, record.name.size());
students.push_back(record);
}

sort(students.begin(), students.end(), compare);

for (std::vector::size_type i = 0; i != students.size(); ++i){
cout << setw(maxlen+1) << students[i].name;

try {
double final_grade = grade(students[i]);
streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3) << final_grade << setprecision(prec) << endl;
} catch (domain_error e) {
cout << e.what();
}
cout << endl;
}
return 0;
}