Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
std::optional
C++17 adds template std::optional
to manage an optional value.
DIY
Try to make pass the tests for error cases. Do not worry about the good case test, if it fails because of formating or precision issues.
Make the tests pass by refactoring function differentiate
to return std::optional<double>
instead of double
.
Does it help to make use of value_or()
?
Refactor the code to use std::optional
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <functional>
#include <sstream>
#include <string>
// symmetric difference quotient
double differentiate(std::function<double(double)> f, double h, double x)
{
return (f(x + h) - f(x - h)) / (2 * h);
}
std::string estimated_velocity(std::function<double(double)> distance, double time, double precision)
{
auto velocity = differentiate(distance, precision, time);
std::stringstream output;
output << "Estimated velocity after " << time << " seconds is " << velocity << " m/s.";
return output.str();
}
Enter to Rename, Shift+Enter to Preview
Bonus exercise
Replace the type for time with something better than than double.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content