Help with finding average

So I am trying to find the average of 4 numbers (assignment grades) and I can't seem to get the correct numbers. Here are the 4 numbers: 75, 85, 82, 94 respectively. I get 254 as the sum and 63 as the average. I realize that I don't need to calculate the sum first and then divide by 4 but I am attempting to try everything here. If someone could help me that would be great... I'm about to rip my hair out over here.
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
#include <iostream>

using namespace std;

int main()
{
    int assign1;
    int assign2;
    int assign3;
    int assign4;
    int assignavg;
    int assignsum;
    cout << "Enter the score for the first assignment: ";
    cin >> assign1;

    cout << "Enter the score for the second assignment: ";
    cin >> assign2;

    cout << "Enter the score for the third assignment: ";
    cin >> assign3;

    cout << "Enter the score for the fourth assignment: ";
    cin >> assign3;

    assignsum = assign1 + assign2 + assign3 + assign4;

    cout << assignsum << endl;

    assignavg = assignsum / 4;

    cout << assignavg << endl;

    return 0;
}
Last edited on
closed account (2UD8vCM9)
Well one issue that I see.
1
2
3
4
5
6
7
8
9
10
11
cout << "Enter the score for the first assignment: ";
cin >> assign1;

cout << "Enter the score for the second assignment: ";
cin >> assign2;

cout << "Enter the score for the third assignment: ";
cin >> assign3;

cout << "Enter the score for the fourth assignment: ";
cin >> assign3;


You accidentally assign the fourth assignment grade to assign3 instead of assign4. You never actually set assign4 to anything because of this.

Another problem is that assignavg is an integer. Integers can only be whole numbers, so it wont be an accurate average. To fix this, we can change assignavg to be a float.

The modified code should look something like this

Also since we changed assignavg to a float, we need to divide assignsum by 4.0 instead of 4 so that we get back a float result instead of the integer result (when we just divide an integer by an integer).
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
#include <iostream>

using namespace std;

int main()
{
	int assign1;
	int assign2;
	int assign3;
	int assign4;
	float assignavg;
	int assignsum;
	cout << "Enter the score for the first assignment: ";
	cin >> assign1;

	cout << "Enter the score for the second assignment: ";
	cin >> assign2;

	cout << "Enter the score for the third assignment: ";
	cin >> assign3;

	cout << "Enter the score for the fourth assignment: ";
	cin >> assign4;

	assignsum = assign1 + assign2 + assign3 + assign4;

	cout << assignsum << endl;

	assignavg = assignsum / 4.0;

	cout << assignavg << endl;
	system("pause");
	return 0;
}
Last edited on
Wow, how did I not notice that!!! Thanks so much.
Topic archived. No new replies allowed.