简体   繁体   中英

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. 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.

#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. If you don't initialize vector with a size then you can use push_back() to insert elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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