tags:

views:

190

answers:

4

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

+2  A: 

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.

280Z28
Yeah, this is likely to be what the OP wants (though the question isn't clear about what this integer should represent).
Noldorin
I'm given a distance as integer and a time in lbltime.text, I then need to calculate the avg speed.
+5  A: 

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 :)

Matt Howells
This works, but if he doesn't need to display the integer, the `Ticks` property doesn't require any scaling.
280Z28
yip this works. But how can I use this to calculate and avg speed.distance/time=avg speed
@Lance, I suggest you amend your question regarding the speed calculation.
Matt Howells
+3  A: 

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.

Mark Seemann
+1  A: 

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;
awe