我有以下代码
for (int i = 0; i < courses; i++)
{
cout << "Please Enter Letter Grade: ";
cin >> grade1;
cout << "Please Enter Course Weighting: ";
cin >> weight1;
}
现在,可以说循环运行了3次,并且用户为grade1
和weight1
输入的值每次都不同。我想存储这些不同的值,以便可以对它们进行一些计算。我将如何进行呢?
答案 0 :(得分:2)
这里是使用数组的方式:
int grade[courses]; // this is an array with size of courses
double weight[courses];
for (int i = 0; i < courses; i++) {
cout << "Please Enter Letter Grade: ";
cin >> grade[i];
cout << "Please Enter Course Weighting: ";
cin >> weight[i];
}
数组是顺序存储在计算机内存中的相同类型数据的集合。数组的语法如下:
<type> <name>[<size>];
例如
int numberOfStudents[100];
是int
数组,最多包含100个元素。
H 操作 T 他的 H 后腿
答案 1 :(得分:2)
将grade
和weight
分组为struct,并将它们存储在vector中。
代码:(不处理所有潜在的错误)
#include <iostream>
#include <vector>
struct grade_weight
{
int grade;
int weight;
};
int main()
{
int courses = 5;
std::vector<grade_weight> result;
// potential optimization if you want
//result.reserve(courses);
for (int i = 0; i < courses; i++)
{
int grade, weight;
std::cout << "Please Enter Letter Grade: ";
std::cin >> grade;
std::cout << "Please Enter Course Weighting: ";
std::cin >> weight;
result.push_back({grade, weight});
}
std::cout << "you input\n";
for(auto& gw: result)
{
std::cout << "grade: " << gw.grade << ", weight: " << gw.weight << '\n';
}
}