Losing data while using functions

This program takes in 4 ints and calculates sum, average, and product using functions. My issues is that the average function does not return a double but an int...

3 4 5 6
3 4 5 6
Your sum is: 18
Your average is: 4
Your product is: 360

As you can see I inputted 3 4 5 6 which averages to 4.5, but the average function is returning 4. I don't understand why because I have set the variable to double

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
using namespace std;

void Get_Value(int& value);
void Display_Value(int val);
int Calc_Sum(int a, int b, int c, int d);
int Calc_Product(int w, int x, int y, int z);
double Calc_Ave(int sum, int num_items);
void Display_Results(int sum, int product, double average);

int main()
{
	int a, b, c, d, sum, product, item_num = 4;
	double average;
	Get_Value(a);
	Get_Value(b);
	Get_Value(c);
	Get_Value(d);
        Display_Value(a);
        Display_Value(b);
        Display_Value(c);
        Display_Value(d);
	sum = Calc_Sum(a, b, c, d);
	product = Calc_Product(a, b, c, d);
	average = Calc_Ave(sum, item_num);
	cout << average;
	Display_Results(sum, product, average);

	system("pause");
	return 0;
}

void Get_Value(int& value)
{
	cin >> value;
}

void Display_Value(int val)
{
	cout << val << " ";
}

int Calc_Sum(int a, int b, int c, int d)
{
	int sum;
	sum = a + b + c + d;
	return sum;
}

int Calc_Product(int w, int x, int y, int z)
{
	int product;
	product = w * x * y * z;
	return product;
}

double Calc_Ave(int sum, int num_items)
{
	double average;
	average = sum / num_items;
	return average;
}

void Display_Results(int sum, int product, double average)
{
	cout << "\nYour sum is: " << sum << endl;
	cout << "Your average is: " << average << endl;
	cout << "Your product is: " << product << endl;
}
1
2
3
4
5
6
7
8
9
double Calc_Ave(int sum, int num_items) // invariant: num_items > 0 
{
	double average;

	// average = sum / num_items; // integer division: 18 / 4 == 4
        average = double(sum) / num_items ; // 18.0 / 4 == 4.5 

	return average;
}


Shorter and sweeter:
1
2
3
4
5
double Calc_Ave(int sum, int num_items)
{
        const double average = double(sum) / num_items ; 
	return average;
}


Or just:
1
2
3
4
double Calc_Ave(int sum, int num_items)
{
        return  double(sum) / num_items ; 
}
Topic archived. No new replies allowed.