This question is asked multiple time’s, but i can’t get it working…
I’m working on an program that calculates the distance between two points, and the calculates the time an unit walks about it…
This is the simplefied version of what i need to do:
x = 24
y = 23
Root of (24² + 23²) = 33.24 fields
33.24 x 30 = 997,2 minuts
997,2/60 = 16,62 hours
16: (60*0.62) = 16:37,2
16:37: (60*0,2) = 16:37:12
So i’ve got this piece of code in C#, but it isn’t working:
first_town = "35|629";
second_town = "59|606";
snelheidUnit = 30;
string[] firstTownSplit = first_town.Split('|');
string[] secondTownSplit = second_town.Split('|');
int firstTownPart1 = Convert.ToInt32(firstTownSplit[0]);
int firstTownPart2 = Convert.ToInt32(firstTownSplit[1]);
int secondTownPart1 = Convert.ToInt32(secondTownSplit[0]);
int secondTownPart2 = Convert.ToInt32(secondTownSplit[1]);
int verschilX = firstTownPart1 - secondTownPart1;
int verschilY = firstTownPart2 - secondTownPart2;
double aantalVelden = Math.Sqrt((Math.Pow(verschilX, 2) + Math.Pow(verschilY,2))); // Fields
double aantalMinuten = aantalVelden * snelheidUnit; // Minuts
double aantalUren = aantalMinuten / 60; // Hours
TimeSpan time = TimeSpan.FromHours(aantalUren);
string FinalTime = string.Format("{0:D2}d:{1:D2}h:{2:D2}m:{3:D2}s:{4:D3}ms", time.Days, time.Hours, time.Minutes, time.Seconds, time.Milliseconds);
The expected output should be: 00d:16h:37m:12s:772ms
But is: 00d:16h:37m:14s:772ms
The difrnce is 2 seconds. What is the bottleneck? Why is there 2 seconds difrnce between the expected output and the real output?
The square root of
1105isn’t exactly33.24; you only get33.24if you round the square root. So compare your problem description:against what happens with a more precise value for the square root:
which is about 2 seconds different from what you are getting
If you want to reproduce your original calculation, you need to do something after
to round that in the same way as your original; for example,