Need Help with division Issue

This code is supposed to calculate the speed(mph) traveled, by entering the miles traveled and the time it took. This issue is when I enter 5 for "miles" and 2 for "hours", the out come is 2.00 instead of 2.50. What is the issue?

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
29
30
31
32
33
34
35
36
37
 #include <iostream>
#include <iomanip>
using namespace std;

float milesPerHour (int miles, int hours);

int main()
{
	int miles,
	    hours;
	float mph;
	
	
	cout << setprecision(2) << fixed << showpoint;
	cout << "Miles Traveled :"<< endl;
	cin >> miles;
	cout << "Hours Traveled :"<<endl;
	cin >> hours;
	
	mph=milesPerHour ( miles, hours);
	// Fill in code necessary to call milesPerHour
	cout << mph << endl;
	// Print result

	return 0;
}	


float milesPerHour (int miles, int hours)
{
	float mph;
	cout << setprecision(2) << fixed << showpoint;
	mph= miles/hours;
	//Fill in the code to calculate the miles per hour and return to main
	
	return mph;
}
You divide 2 integers by each other, which will result in an integer. See this article for more info on integer division: https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division

To fix your problem, you have a 2 options:
1. change the signature of milesPerHour to take float or double values instead of integers.
2. cast either miles or hours to a float or double:
 
mph = (float)miles / hours;
Thank You!
Topic archived. No new replies allowed.