Can formulas be put into header files?

So I have to create a program that asks the user for the amount of miles and gallons that they used in their car for the trip and compute the miles per gallon and miles per gallon total. So is there any way that I can corporate the formulas like totalMiles += miles and if(gallons != 0) then totalGallons += gallons in the header file?
This is my header file below

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
40
41
42
43
44
45
46
class Distance
{
public:
    Distance(){};
    Distance(double carMiles, double carGallons, double totalMiles, double totalGallons, double milesPerGallons, double milesPerGallonsTotal)
            : miles{carMiles}, gallons{carGallons}, milesTotal{totalMiles}, gallonsTotal{totalGallons}, milesAndGallons{milesPerGallons}, milesAndGallonsTotal{milesPerGallonTotal} {}
    void setMiles(double carMiles)
    {
        miles = carMiles;
    }
    void setGallons(double carGallons)
    {
        gallons = carGallons;
    }
    void setMilesTotal(double totalMiles)
    {
        milesTotal = totalMiles;
    }
    void setGallonsTotal(double totalGallons)
    {
        gallonsTotal = totalGallons;
    }
    void setMilesAndGallons(double milesPerGallon)
    {
        milesAndGallons = milesPerGallon;
    }
    void setMilesAndGallonsTotal(double milesPerGallonTotal)
    {
        milesAndGallonTotal = milesPerGallonTotal;
    }
    double getMiles() const {return miles;}
    double getGallons() const {return gallons;}
    double getMilesTotal() const {return milesTotal;}
    double getGallonsTotal() const {return gallonsTotal;}
    double getMilesAndGallons() const {return milesAndGallons;}
    double getMilesAndGallonsTotal() const {return milesAndGallonsTotal;}

private:
    double miles;
    double gallons;
    double milesTotal;
    double gallonsTotal;
    double milesAndGallons;
    double milesAndGallonsTotal;
};
Formulae, specified as inline functions (or as functions with internal linkage) can be placed in header files.
can you suggest on how I can do that and then call it in my cpp file
Here is an example:

header point.h
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
#ifndef HEADER_POINT_H_INCLUDED
#define HEADER_POINT_H_INCLUDED

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <algorithm>

struct point { int x = 0 ; int y = 0 ; };

inline std::ostream& operator<< ( std::ostream& stm, point p )
{ return stm << '(' << p.x << ',' << p.y << ')' ; }

inline double euclidean_distance( point a, point b )
{
    const int dx = a.x - b.x ;
    const int dy = a.y - b.y ;
    return std::sqrt( dx*dx + dy*dy ) ;
}

inline int taxicab_distance( point a, point b )
{
    const int dx = a.x - b.x ;
    const int dy = a.y - b.y ;
    return std::abs(dx) + std::abs(dy) ;
}

inline int chebyshev_distance( point a, point b )
{
    const int dx = a.x - b.x ;
    const int dy = a.y - b.y ;
    return std::max( std::abs(dx), std::abs(dy) ) ;
}

#endif // HEADER_POINT_H_INCLUDED 


cpp file (say, formulae_in_headers_example.cpp)
1
2
3
4
5
6
7
8
9
10
11
12
#include "point.h"

int main()
{
    point a { 10, 20 } ;
    point b { 290, 470 } ;

    std::cout << "distance from " << a << " to " << b << '\n'
              << "euclidean: " << euclidean_distance(a,b) << '\n'
              << "  taxicab: " << taxicab_distance(a,b) << '\n'
              << "chebyshev: " << chebyshev_distance(a,b) << '\n' ;
}
But can it be done if a user has to input the numbers ?
why don't you try it and see?
What if the users does:
Distance d;
1
2
3
4
5
6
d.setMiles(1000);
d.setGallons(50);
d.setMilesAndGallons(1);
d.setMilesTotal(100);
d.setGallonsTotal(2);
d.setMilesAndGallonsTotal(200);

Now the object's values don't make sense in the real world. How can they have traveled 1000 miles in this trip and only 200 miles total? If they travelled 1000 miles on 50 gallons then they got 20 miles per gallon, but if you ask for the mileage, it will return 1, due to the call to setMilesAndGallons().

Logically, the way to modify the class is to add a new trip. That means adding both the miles and the gallons at the same time. Store the trip miles and gallons, as well as the overall totals. Compute the miles per gallon from miles and gallons. That way it's impossible for it to be inconsistent. With this interface, it's impossible for the values to become inconsistent:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Distance
{
public:
    Distance() :
        tripMiles(0.0), tripGallons(0.0),
        totalMiles(0.0), totalGallons(0.0)
    {}
    void addTrip(double miles, double gallons) {
        tripMiles = miles;
        tripGallons = gallons;
        totalMiles += miles;
        totalGallons += gallons;
    }
    double getTripMiles() const {return tripMiles;}
    double getTripGallons() const {return tripGallons;}
    double getMilesTotal() const {return totalMiles;}
    double getGallonsTotal() const {return totalGallons;}
    double getTripMPG() const {return tripMiles / tripGallons; }
    double getTotalMPG() const {return totalMiles / totalGallons; }

private:
    double tripMiles, tripGallons; // miles & gallons for current trip
    double totalMiles, totalGallons; // miles & gallons total
};


Last edited on
here is my main file..
When i run it, the total MPG is doubled the first time so it is not accurate. Does anyone know why?
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
#include <iostream>
#include "Distance.h"
using namespace std;

int main()
{
    Distance myDistance;
    double miles;
    double gallons;
    cout << "Enter miles driven (-1 to quit): ";
    cin >> miles;
    myDistance.addTrip(miles,gallons);

    while(miles != -1)
    {
        cout << "\nEnter Gallons used: ";
        cin >> gallons;
        myDistance.addTrip(miles,gallons);
        cout << "\nMPG this trip: " << myDistance.getTripMPG();
        cout << "\nTotal MPG is: " << myDistance.getTotalMPG();
        cout << "\nEnter miles driven (-1 to quit): ";
        cin >> miles;
    }
}
Remove addtrips before the loop
Last edited on
closed account (48T7M4Gy)
Another way: ( it would be better to model Trips and sub-tTrips better with a data structure of a trip array or even better an extra Journey class. But a single class does the job, not unlike a mechanical speedometer/trip meter from the Steam Age

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>

class Trip{
private:
    double miles = 0;
    double gallons = 0;
    
    double total_miles = 0;
    double total_gallons = 0;
    
public:
    Trip(double aMiles = 0, double aGallons = 0){
        miles = aMiles;
        gallons = aGallons;
        
        total_miles += miles;
        total_gallons += gallons;
    }
    
    void addTrip(const Trip sub_trip){
        total_miles += sub_trip.miles;
        total_gallons += sub_trip.gallons;
    }
    
    double fuel_consumption(){
        return total_miles / total_gallons;
    }
    
    double total_distance(){
        return total_miles;
    }
    
    double total_fuel(){
        return total_gallons;
    }
};

using std::cin;
using std::cout;
using std::endl;

int main()
{
    Trip myTrip;
    
    double miles;
    double gallons;
    
    while(
          cout << "Enter miles driven (-1 to quit): "
          and cin >> miles
          and miles != -1
          ){
        
        cout << "Enter Gallons used: ";
        cin >> gallons;
        
        myTrip.addTrip( Trip(miles, gallons) );
        
        cout << "  MPG this trip: " << miles/gallons << endl;
        cout << "   Total MPG is: " << myTrip.fuel_consumption() << endl;
        cout << "Total travelled: " << myTrip.total_distance() << endl;
        cout << "     Total fuel: " << myTrip.total_fuel() << endl << endl;
    }
}
Enter miles driven (-1 to quit): 10
Enter Gallons used: 2
  MPG this trip: 5
   Total MPG is: 5
Total travelled: 10
     Total fuel: 2

Enter miles driven (-1 to quit): 15
Enter Gallons used: 3
  MPG this trip: 5
   Total MPG is: 5
Total travelled: 25
     Total fuel: 5

Enter miles driven (-1 to quit): 25
Enter Gallons used: 7
  MPG this trip: 3.57143
   Total MPG is: 4.16667
Total travelled: 50
     Total fuel: 12

Enter miles driven (-1 to quit):
Last edited on
closed account (48T7M4Gy)
So is there any way that I can corporate the formulas like totalMiles += miles and if(gallons != 0) then totalGallons += gallons in the header file?


There is nothing sacred about header files so call them what you like eg "xyz_whatever_no_dot" and put any functions you like inside the class as a method and/or outside as a completely separate function. Give them the same name and see how that works. Try it out.

There are conventions involved but none that will break anything or blow up the linking if you decide to ignore them. Obviously file names have to be correct and c++ rules on syntax still apply etc.

As far as the mpg calculation requiring >0 gallons it is not unreasonable to force the users to meet a precondition of the function, if it is made clear, that gallons must be >0 and one simple way to handle that is by way of exception handling or some other simple error capture if statement in main(). Unless you really want them to be inline ( eg you want to enhance performance, and why not) the 'inline' keyword isn't a mandatory requirement).
Topic archived. No new replies allowed.