mpg and mpd calculator

I am a beginner to c++ and i need to write a miles per gallon and miles per dollar code. i wrote one but my professor said i need to use functions and arrays. can anyone help me modify my current code?

#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
double mpg; // run without debugging
double mpd;
int i = 0;

while (i <= 4)
{

cout << "Please enter your trip mileage: ";
double miles;
cin >> miles;
cout << "Please enter the amount of gas to the 3rd decimal point: ";
double gas;
cin >> gas;
cout << "Enter cost of gas: $";
double cost;
cin >> cost;

mpg = miles / gas;
mpd = mpg / cost;

cout << fixed << setprecision(4) << "Your car's miles per gallon is " << mpg << "." << endl;
cout << fixed << setprecision(2) << "Your miles per dollar is $" << mpd << "." << endl;

i++;

}

system("pause");
return 0;
}
I can help you but a few things first, make sure you use the code brackets so that it's easier for others to read your code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
double mpg;	// run without debugging 
double mpd;
int i = 0;

while (i <= 4)
{

cout << "Please enter your trip mileage: ";
double miles;
cin >> miles;
cout << "Please enter the amount of gas to the 3rd decimal point: ";
double gas;
cin >> gas;
cout << "Enter cost of gas: $";
double cost;
cin >> cost;

mpg = miles / gas;
mpd = mpg / cost;

cout << fixed << setprecision(4) << "Your car's miles per gallon is " << mpg << "." << endl;
cout << fixed << setprecision(2) << "Your miles per dollar is $" << mpd << "." << endl;

i++;

}

system("pause");
return 0;
}


Also I wouldn't use system pause, it's a bad habit and won't work on every system that might possibly run your code.

As far as a function goes though, you can declare it above your main or below your main. If you declare it below your main, then you need a function prototype above it. If it's above then you do not. To call a function in your main simply type in the function name.

Here's a short function as an example:

1
2
3
4
void welcome_message() {
cout << "I'm a function" << endl;
}


Then to call this in your main, so that it would display, you would simply type welcome_message();

There's a few videos that you'll need to look up. Good luck :)

As far as arrays go, have you ever used one before?
Last edited on
Topic archived. No new replies allowed.