简体   繁体   English

我不知道如何用变量写平均成绩

[英]I don't know how to write the average grade with variables

I'm trying to automatically set the number of the given variables, for example:我正在尝试自动设置给定变量的数量,例如:

char subject1[30];
char subject2[30];
char subject3[30];
float grade1;
float grade2;
float grade3;

cout << "Type in your first subject: "  ;
cin >> subject1;
cout << "Type in your second subject: ";
cin >> subject2;
cout << "Type in your third subject: ";
cin >> subject3;

cout << "Type in your grade for: " << subject1 << " :";
cin >> grade1;
cout << "Type in your grade for: " << subject2 << " :";
cin >> grade2;
cout << "Type in your grade for: " << subject3 << " :";
cin >> grade3;


float sum = grade1 + grade2 + grade3;
float average = (sum / 3);


cout << "AVERAGE GRADE";
cout << "************************************" << endl;
cout << subject1 << grade1 << endl;
cout << subject2 << grade2 << endl;
cout << subject3 << grade3 << endl;
cout << "====================================" << endl;
cout << "Average: " << average << endl;

return 0;

The code that calculates it works but I was wondering as how do I put the 3 grades that user inputed.计算它的代码有效,但我想知道如何放置用户输入的 3 个等级。 So I don't have to go edit the calculation part every time I add another subject.所以我每次添加另一个主题时都不必去编辑计算部分。 I'm not sure if I explained well as to what I meant but I hope you understand.我不确定我是否解释清楚我的意思,但我希望你能理解。

A simple solution would be to store everything in a vector (that's preferred most of the time over the char array you used) an then just loop for the amount of subjects you have.一个简单的解决方案是将所有内容都存储在一个vector (大多数情况下,这比您使用的char array受欢迎),然后就您拥有的主题数量进行循环。

#include <vector>   // need to inlcude this to be able to use vector
#include <iostream>

const int numSubjects = 3;

std::vector<std::string> prefix{"first", "second", "third"};
std::vector<std::string> subjects(numSubjects);
std::vector<float> grades(numSubjects);

for(int i = 0; i < numSubjects; i++) {
    std::cout << "Type in your " << prefix[i] << " subject: ";
    std::cin >> subjects[i];
    std::cout << "Type in your grade for " << subjects[i] << ": ";
    std::cin >> grades[i];
}

//afterwards do the calculations

Note that I initialized the vectors with a size of numSubjects that way you can access and write to indices of the vector with the [] operator.请注意,我用numSubjects的大小初始化了向量,这样您就可以使用[]运算符访问和写入向量的索引。 If you don't initialize vector with a size then you can use push_back() to insert elements.如果不使用大小初始化vector ,则可以使用push_back()插入元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM