Velocity Calculation gone wrong

The numbers I need to input test are as following:
Start milepost? 321
Elapsed time (hours minutes seconds)? 2 15 36
End milepost? 458
The result should be that the car traveled 137 miles in 2 hrs 15 min and 36 sec.
That is correct.
The only thing wrong is that the average velocity SHOULD be 60.6195 mph.
I am receiving a value of 68.5.

Here is my code, please help, and explain if you would be so kind.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
	//starting milespost
	cout << "Start milespost? ";
	int startingmilespost;
	cin >> startingmilespost;

	//elasped time
	cout << "Elapsed time (hours minutes seconds)? ";
	int hours;
	int minutes;
	int seconds;
	cin >> hours;
	cin >> minutes;
	cin >> seconds;

	//end milespost
	cout << "End milespost? ";
	int endmilespost;
	cin >> endmilespost;

	//calculation
	float traveled;
	traveled=endmilespost-startingmilespost;
	float hourstotal;
	hourstotal=(hours)+(minutes/60)+(seconds/3600);
	float velocity;
	velocity=traveled/hourstotal;
	cout << "Car went " << traveled << " miles in " << hours << " hrs " << minutes << " min " << seconds << " sec " << endl;
	cout << "Average velocity was " << velocity << " mph" << endl;
Have you considered using long double instead of float? Also, I think you need more precise calculations when calculating the average velocity.
Last edited on
Yeah a float is best for about 7 digits (excluding the 0s ) AFAIK
ex:
3.14
3.000000014
is better with float vs double
hourstotal=(hours)+(minutes/60)+(seconds/3600);
hours, minutes and seconds are all integers. So, minutes / 60 and seconds / 3600 result in integer division, and the result of that division is 0. Try casting minutes and seconds to floats:

hourstotal=(hours)+((float)minutes/60)+((float)seconds/3600);

Edit:
Or if you chose to change to double or long double, cast them to that. Damn ninjas are breaking the internet. Had to reload nearly a dozen times before the page would actually come up.
Last edited on
I think you're running into an integer division problem (whereby the remainder is thrown away). You are getting minutes/60 = 0 and seconds/3600 = 0 giving hourstotal = 2 exactly (which fits your result).

Force floating point division by making one number a float value. Try replacing line 24 with
hourstotal=(hours)+(minutes/60.0f)+(seconds/3600.0f);
Last edited on
This worked, thank you so much everybody! I guess dividing integers is not something that should be done for precision.
I did as Danny Toledo said and casted the minutes and seconds to floats and that seemed to fix all of my issues.
Or, alternatively:

hourstotal = (hours) + (minutes/60.0) + (seconds/3600.0);
Last edited on
I would suggest xismn's method it is more accurate since doubles are twice as precise as floats.
Topic archived. No new replies allowed.