answersLogoWhite

0

To calculate speed you need to know the distance travelled and the time taken to travel that distance such that Speed = Distance / Time. The result of this calculation gives the average speed without taking into account any periods of acceleration or deceleration. We can implement this using just one function:

long double speed (const long double distance, const long double duration) {

return distance / time; }

Note that we use the term "duration" rather than "time" purely to aid readability; "time" implies a specific moment in time rather than a duration.

We use a long double to cater for the widest possible range of values. However, if we want to ensure the most efficient calculation over a wide variety of numeric types, we would use a function template instead:

template<typename T>

T speed (const T& distance, const T& duration) {

return distance / duration;

}

The distance and duration variables will typically be taken from input:

int main () {

double distance, duration;

std::cout << "Enter the distance and duration: "

std::cin >> distance >> duration;

std::cout << "Speed = " << speed (distance, duration) << '\n';

}

Note that the actual units of measurement are not important to the function because speed is denoted by the given distance per given time unit. That is, if we travel 100 meters in 10 seconds, then the speed is 10 meters per second, whereas if we travel 100 miles in 10 minutes, then we are travelling at 10 miles per minute. Thus when distance is 100 and duration is 10, the speed is 10. It is up to the caller to convert these units to something more meaningful:

int main () { double distance, duration; std::cout << "Enter the distance in kilometers: ";

std::cin >> distance;

std::cout << "Enter the duration in hours: ";

std::cin >> duration;

std::cout << "Speed = " << speed (distance, duration) << " kilometers per hour\n";

}

Note that the examples do not perform any error-checking upon the input. In production code when entering numbers from input you will typically input strings instead. You will then test the strings are valid before typecasting the strings to a numeric format such as double.

User Avatar

Wiki User

9y ago

What else can I help you with?