Is that because every function that I have then has access to the variables and it can be confusing to see which function is using it when first starting out? |
Pretty much, if you can limit the code that has access to a variable it's easier to know which code is modifying it. Even if you are an expert, you can only focus on so many things at one time.
double g1, g2, g3 = 0;
This might not be an error but I don't think it does what you intended. g3 is initialized to 0, g1 and g2 are left undefined.
You could write ...
double g1 = 0, g2 = 0, g3 = 0;
Or maybe even better, write 3 separate lines
1 2 3
|
double g1 = 0;
double g2 = 0;
double g3 = 0;
|
It's a good idea to define variables just before they are used, that way you always have a meaningful value to put in them straight away. And it limits some possible mistakes you could make (like if you wrote g3 where you meant to write g1).
Do you notice in your grades function how a lot of the code looks like a copy/paste job. The only thing that is different is the text message and the variable, so you could write a function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
double input_grade(const std::string& grade_str)
{
std::cout << "Please enter in your " << grade_str << " grade 0-100\n";
double grade_num;
std::cin >> grade_num;
while(grade_num > 100 || grade_num < 0)
{
std::cout << "Please enter in your " << grade_str << " grade 0-100, whole numbers only please.\n";
std::cin >> grade_num;
}
return grade_num;
}
|
Now you only have to check one piece of code for errors, instead of three parts.
You could use that function like this...
1 2 3 4 5 6 7 8
|
double grades()
{
const double g1 = input_grade("first");
const double g2 = input_grade("second");
const double g3 = input_grade("third");
return (g1 + g2 + g3) / 3;
}
|