c++ - 有什么方法可以将来自用户输入的多个 int 存储到向量中?
问题描述
我试图通过让用户输入他们收到的成绩来将多个 int 存储到一个向量中。但是我确实相信有一个更简化的版本来尝试这样做。有单独的功能会更好吗?有没有人可以指导我正确的方向?
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main() {
cout << "Welcome to the Grade Calculator! \n"
<< "What is the student's full name? ";
string student_name;
getline(cin,student_name);
cout << "\nPlease input the points earned for each assignment.";
vector<int> student_grades(8);
cout << "\nLab 2: ";
cin >> student_grades[0];
cout << "Lab 3: ";
cin >> student_grades[1];
cout << "Lab 4: ";
cin >> student_grades[2];
cout << "Lab 5: ";
cin >> student_grades[3];
cout << "Lab 6: ";
cin >> student_grades[4];
cout << "Lab 7: ";
cin >> student_grades[5];
cout << "Lab 8: ";
cin >> student_grades[6];
cout << "Lab 9: ";
cin >> student_grades[7];
cout << "Lab 10: ";
cin >> student_grades[8];
//Finding sum of the grades
int sum_of_grades = accumulate(student_grades.begin(),student_grades.end(),0);
//Console Output
cout << '\n'<< student_name << " has earned " << sum_of_grades << " points in the course, so far." << endl;
cout << "\nThere are 2000 points possible in this course." << endl;
cout << "\nInput the anticpated score for the final project (200 points possible): ";
int anticipated_score;
cin >> anticipated_score;
int total_score = sum_of_grades+anticipated_score;
cout << "Total Projected Assignment Points: " << total_score << endl;
cout << "\nFinal Exam Score Needed for Final Course Grade (1000 Points Possible)"
<< "\nTo Earn an A, need at least: " << 1800 - total_score << " points, for a total of: 1800"
<< "\nTo Earn a B, need at least: " << 1600 - total_score << " points, for a total of: 1600"
<< "\nTo Earn a C, need at least: " << 1400 - total_score << " points, for a total of: 1400"
<< "\n To Earn a D, need at least: " << 1200 - total_score << " points, for a total of: 1200" << endl;
return 0;
}
解决方案
您可以使用 for 循环:
for(int i = 0; i < 8; ++i){
cout << "\nLab " << i+2 << ": ";
cin >> student_grades[i];
}
该代码本质上等同于您在程序中编写的代码;它遍历所有可能的索引,提示用户在vector
.
推荐阅读
- c++ - 如何启用 -mno-outline-atomics AArch64 标志?
- ruby-on-rails - Stripe Connect with React and API only Rails
- html - css 不同的图像不同的宽度
- java - 我必须通过 MyObject 进行迭代的练习问题
- react-native - Open a new screen through a tab screen
- python - Can websockets "lag" when a lot of messages are received?
- unit-testing - Unit Testing a custom TagHelper where HTML conditionally rendered based on the presence of a ValidationAttribute on the model Property
- microsoft-graph-api - 带有 Azure AD B2C 的 Microsoft Graph API:获取所有用户及其组成员身份
- email - Enable TLS 1.2 for mail sub system on jboss wildfly
- python - How to define values in python constructor, so it can be used from method level