Lance
Lance

Reputation:

Calculate Avg Speed

Given a distance (50km) as integer: 50

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

hh:mm:ss.ms

How would I calculate the avg speed in km/h?

Thanks

Lance

Upvotes: 3

Views: 5598

Answers (4)

awe
awe

Reputation: 22442

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

This will give you km/h as you asked for:

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

Upvotes: 2

Matt Howells
Matt Howells

Reputation: 41266

Here you go:

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

As I am not near a compiler, your mileage may vary :)

Upvotes: 5

Mark Seemann
Mark Seemann

Reputation: 233150

The short answer is:

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

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

A more object-oriented answer includes defining Value Object classes for Distance and Speed. Just like TimeSpan is a value object, you could encapsulate the concept of distance irrespective of measure in a Distance class. You could then add methods (or operator overloads) than calculates the speed from a TimeSpan.

Something like this:

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

If you only need to calculate speed a few places in your code, such an approach would be overkill. On the other hand, if working with distances and velocities are core concepts in your domain, it would definitely be the correct approach.

Upvotes: 5

Sam Harwell
Sam Harwell

Reputation: 99869

What are you using the integer for? The TimeSpan.Ticks property is a 64-bit integer that you can then pass back to the TimeSpan constructor.

Upvotes: 2

Related Questions