当我检查homework使用向量的内部值时cout,似乎只返回内部的值homework[0]。有人可以查看我的代码并让我知道我要去哪里了吗?
int main()
{
cout << "Please enter midterm and final: " << endl;
double midterm, gfinal;
cin >> midterm >> gfinal;
cout << "Enter all your homework grades, " << endl;
double x;
cin >> x;
// initing a vector object named homework
vector<double> homework;
// show debug on the vector
while (homework.size() != 3)
homework.push_back(x);
if (homework.size() == 0)
{
cout << endl << "You need to enter at least one number";
return 1;
}
// vector before sorting
// since cout << homework did not seem to work I could always just write a debug function to iterate over structures and print them to the console
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
// sort the vector here
sort(homework.begin(), homework.end());
// vector after sorting
//cout << homework;
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
int mid = homework.size() / 2;
cout << "The below is mid" << endl;
cout << mid << endl;
double median;
if (homework.size() % 2 == 0)
median = (homework[mid - 1] + homework[mid]) / 2;
else
median = homework[mid];
//streamsize prec = cout.precision(3);
cout << "Your course grade is "
<< 0.2 * midterm + 0.4 * gfinal + 0.4 * median << endl;
//cout.precision(prec);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是引起我困惑的特定代码:
// vector before sorting
// since cout << homework did not seem to work I could always just write a debug function to iterate over structures and print them to the console
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
// sort the vector here
sort(homework.begin(), homework.end());
// vector after sorting
//cout << homework;
cout << homework[0] << endl;
cout << homework[1] << endl;
cout << homework[2] << endl;
Run Code Online (Sandbox Code Playgroud)
程序启动时,它要求2个值,所以我插入了100100。然后它要求3个值,所以我使用80 90 100时cout,所有作业的位置在我期望80 90 100时都显示80。实际的程序有效最终的cout收益为92。
在您的代码中:
double x;
cin >> x; // <-- reading from cin only once
// initing a vector object named homework
vector<double> homework;
// show debug on the vector
while (homework.size() != 3)
homework.push_back(x); // <- inserting same value three times
Run Code Online (Sandbox Code Playgroud)
您只读取cin一次,即您正在读取一个值。然后,您将读取的值插入到vector中三次homework。因此,homework[0],homework[1]和homework[2]包含相同的值。
考虑将其cin >> x放入while循环中以从中读取三次,cin而不是一次,即cin在循环的每次迭代中进行读取:
vector<double> homework;
while (homework.size() < 3) {
double x;
cin >> x;
homework.push_back(x);
}
Run Code Online (Sandbox Code Playgroud)