Hi,
The first stop is to compile the program with all the warnings on - I did this with cpp.sh - the Gear icon top right of the code. Turn on all 3 warning levels. This is the result:
In function 'int main()':
41:22: warning: 'pergals' may be used uninitialized in this function [-Wmaybe-uninitialized]
46:68: warning: 'gals' may be used uninitialized in this function [-Wmaybe-uninitialized] |
So a golden rule in coding is to
always initialise your variables to something. In C++ one can often delay the declaration until there is a sensible value to assign to it. Otherwise assign a tell-tale value upon declaration that will show an obviously erroneous number. For example set
PricePerGallon
to
1000.0
That way, if you fail to assign a sensible value it should be obvious in the output.
Declaring and assigning just before needed also avoids the declaration of multiple variables on 1 line, and aids understanding.
Why are some of your variables float and some double? double is the default - stick to that.
Also, I would recommend using meaningful variable names, a lot of people have this misconception that they need to abbreviate everything when coding. Good variable and function names leads to code that is self documenting and tells a story of what is happening.
Lines 27 to 29 & 41: I find this a little counter intuitive, why can't you subtract the odometer readings, then add to a sum?
With this:
34 35 36
|
cout << "You'll need to enter price-per-gallon of 3 service stations." << endl;
for (fors = 0; fors <= 4; fors++)
{
|
The idiomatic for loop looks like this:
34 35 36 37
|
cout << "You'll need to enter price-per-gallon of 3 service stations." << endl;
const unsigned int NumOfStations = 3;
for (fors = 0; fors < NumOfStations; fors++)
{
|
I made another
const
variable instead of having a "magic" number in the code. As mentioned earlier, choose good variable names, you can do better than
fors
My
NumOfStations
could be used later on line 47 rather than
fors
Also there is no need to increment the
fors
counter again at the end of the loop on line 42.
Good Luck !!