9.5. Modifiers¶
Of course, sometimes you want to modify one of the arguments. Functions that do are called modifiers.
As an example of a modifier, consider increment, which adds a given
number of seconds to a time object. Again, a rough draft of this
function looks like:
void increment (time& time, double secs) {
time.second += secs;
if (time.second >= 60.0) {
time.second -= 60.0;
time.minute += 1;
}
if (time.minute >= 60) {
time.minute -= 60;
time.hour += 1;
}
}
The first line performs the basic operation; the remainder deals with the special cases we saw before.
Is this function correct? What happens if the argument secs is much
greater than 60? In that case, it is not enough to subtract 60 once; we
have to keep doing it until second is below 60. We can do that by
replacing the if statements with while statements:
The active code below uses the increment function.
Run the active code to see what the output is!
1#include <iostream>
2
3struct time {
4 int hour, minute;
5 double second;
6};
7
8void print_time (time& t) {
9 std::cout << t.hour << ':' << t.minute << ':' << t.second << '\n';
10}
11
12void increment (time& time, double secs) {
13 time.second += secs;
14 while (time.second >= 60.0) {
15 time.second -= 60.0;
16 time.minute += 1;
17 }
18 while (time.minute >= 60) {
19 time.minute -= 60;
20 time.hour += 1;
21 }
22}
23
24int main() {
25 time current_time = { 9, 14, 30.0 };
26 increment(current_time, 60.0);
27 print_time (current_time);
28}
The solution above is correct, but not very efficient. Can you think of a
solution that does not require iteration? Try writing a more efficient version
of increment in the commented section of the active code below. If you get stuck,
you can reveal the extra problem at the end for help.
1#include <iostream>
2using namespace std;
3
4struct time {
5 int hour, minute;
6 double second;
7};
8
9void print_time (time& t) {
10 cout << t.hour << ':' << t.minute << ':' << t.second << '\n';
11}
12
13void increment (time& time, double secs) {
14 // Write your implementation here.
15}
16
17int main() {
18 time t1 = { 9, 14, 30.0 };
19 increment(t1, 60.0);
20 // Should output "9:15:30"
21 print_time (t1);
22
23 time t2 = { 9, 59, 45.0 };
24 increment(t2, 120.0);
25 // Should output "10:1:45"
26 print_time (t2);
27}
Reveal Problem
Let's write the code for the increment function. increment
adds a number of seconds to a time object and updates the values
of the object.
-
time.hour += hours; } -
int hours = (time.minute + mins) / 60; -
int hours = (time.second + second) / 60; -
int mins = (time.second + secs) % 60; -
int mins = (time.second + secs) / 60; -
time.minute = time.minute + mins - 60 * hours; -
time.second = time.minute + mins - 60 * hours; -
time.second = time.second + secs - 60 * mins; -
time.second = time.second + secs; -
void increment (const time& time, double secs) { -
void increment (time& time, double secs) {