During week 5 of study, learning functions and in particular references passed to and from functions. The following program, in a way, cemented some of the stuff studied. It wasn't a part of the book but since I'm interested in running, I thought I'd write a little program that calculates the average pace of a run given the distance (km) and duration (time) of the run.
#include <iostream>
using namespace std;
const int SECS_IN_MIN = 60;
const int MINS_IN_HOUR = 60;
const int SECS_IN_HOUR = 3600;
struct hms
{
int hour;
int min;
int sec;
};
const hms & pace_is(double distance, hms & duration, hms & rate);
int main()
{
double distance;
hms duration;
hms perkm = {0,0,0};
cout << "Enter distance (km's) run: ";
while (!(cin >> distance))
{
cout << "\nMust enter a number - re-enter: ";
cin.clear();
while (cin.get() != '\n')
continue;
}
cout << "\nEnter duration of run - firstly - hours: ";
while (!(cin >> duration.hour))
{
cout << "\nMust be an integer number - re-enter - hours: ";
cin.clear();
while (cin.get() != '\n')
;
}
cout << "\nEnter minutes (0-59): ";
while (!(cin >> duration.min) || duration.min >= MINS_IN_HOUR)
{
cout << "\nMinutes must be 0 - 59, re-enter - minutes: ";
cin.clear();
while (cin.get() != '\n')
;
}
cout << "\nEnter seconds (0 - 59): ";
while (!(cin >> duration.sec) || duration.sec >= SECS_IN_MIN)
{
cout << "\nSeconds must be 0 - 59, re-enter - seconds: ";
cin.clear();
while (cin.get() != '\n')
;
}
perkm = pace_is(distance,duration,perkm);
cout << "\nThe pace per km is : ";
if (perkm.hour > 0)
cout << perkm.hour << ":";
cout << perkm.min << ":" << perkm.sec << endl;
// exit routine
cout << "\n\n...Press ENTER to Exit System...";
cin.clear();
while (cin.get() != '\n')
continue;
cin.get();
return 0;
}
And now the function pace_is()
It works but I'm not overly happy with the fact of the function pace_is returns a reference to a structure and yet that same structure is passed as a reference to the function; what's the point, no real need to have the function return a reference, it might as well be void.
The above file is listed in the attachment, feel free to download.
| Attachment | Size |
|---|---|
| pace-2.zip | 902 bytes |