Calculate average speed

Given the distance (50 km) as an integer: 50

And time as a string in the following format: 00: 02: 04.05

hh: mm: ss.ms

How to calculate avg speed in km / h?

thanks

A spear

+3
source share
4 answers

Short answer:

int d = 50;
string time = "00:02:04.05";
double v = d / TimeSpan.Parse(time).TotalHours;

This will give you speed ( v) in km / h.

A more object-oriented answer involves defining Value Object classes for Distance and Speed. Just like TimeSpan is a value object, you can encapsulate the concept of distance regardless of the measure in the distance class. Then you can add methods (or operator overloads) than calculate the speed using TimeSpan.

Something like that:

Distance d = Distance.FromKilometers(50);
TimeSpan t = TimeSpan.Parse("00:02:04.05");
Speed s = d.CalculateSpeed(t);

, . , , .

+5

:

double distanceInKilometres = double.Parse("50");
double timeInHours = TimeSpan.Parse("00:02:04.05").TotalHours;
double speedInKilometresPerHour = distanceInKilometres / timeInHours;

, :)

+5

What are you using an integer for? The property TimeSpan.Ticksis a 64-bit integer that can then be passed to the constructor TimeSpan.

+2
source

Matt Howells' answer gives you an average speed in m / s.

This will give you km / h, as you requested:

double distanceInKm = (double)50;
double timeInHours = TimeSpan.Parse("00:02:04.05").TotalHours;
double speedInKmPerHour = distanceInKm / timeInHours;
+2
source

Source: https://habr.com/ru/post/1713031/


All Articles