Gold University of Minnesota M. Skip to main content.University of Minnesota. Home page.
 
 
 

What's inside.

Ta Email

Download Compiler

Final Project

Lab Notes

Office Hours

Schedule

Syllabus

Announcements

Check Grades

 

CSci 1113 Home

 
 

Printer-friendly version

 
Functions: Miles-Per-Gallon Examples

1. Initial version

% cat mileage1.cpp
// miles per gallon function

# include <iostream>
using namespace std;

double mileage( double begin, double end, double gals) // header
{
   double mpg;
  
   mpg = (end - begin) / gals;
  
   return mpg;
  


int main()
{
   double start, finish, gallons, mpg;

   start = 33050.0;
   finish = 33355.0;
   gallons = 13.4;

   mpg = mileage( start, finish, gallons );  // call

   cout << "For distance = " << (finish - start) << " miles and "
        << gallons << " gallons " << "\nthe mileage is "
        << mpg << " mpg\n";

   cout << "End of main" << endl;

   return 0;

}


% g++ mileage1.cpp
% a.out
For distance = 305 miles and 13.4 gallons
the mileage is 22.7612 mpg
End of main



2. Using a function declaration so main() can be the first function
    in the source code file


% cat mileage2.cpp
// miles per gallon function
// use a function declaration

# include <iostream>
using namespace std;

double mileage( double begin, double end, double gals); // declaration

int main()
{
   double start, finish, gallons, mpg;

   start = 33050.0;
   finish = 33355.0;
   gallons = 13.4;

   mpg = mileage( start, finish, gallons );  // call

   cout << "For distance = " << (finish - start) << " miles and "
        << gallons << " gallons " << "\nthe mileage is "
        << mpg << " mpg\n";

   cout << "End of main" << endl;

   return 0;

}

double mileage( double begin, double end, double gals) // header
{
   double mpg;

   mpg = (end - begin) / gals;

   return mpg;

}

% g++ mileage2.cpp
% a.out
For distance = 305 miles and 13.4 gallons
the mileage is 22.7612 mpg
End of main


 
The University of Minnesota is an equal opportunity educator and employer.
CSci 1113: C++ Programming