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.
#include <iostream>
usingnamespace 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;
}
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).
#include <iostream>
usingnamespace 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;
}