Arrays

i'm new in c++ so please help me
what i'm trying to do is enter 5 input then get the average of it w/ the the string for name.

The problem is i can't get the average

#include<iostream>
using namespace std;
int main(){
int a,b,average;
string n;

cout<<"Enter student name: ";
cin>>n;

cout <<"Enter five numbers: "<<endl;
for (a=1;a<6;a++)
{
cout<< a <<": ";
cin>> b;

}
average = b/5;
cout << "The average of " << n << " is " << average << endl;

system("pause");
return 0;
}
1
2
3
4
5
6
7
8
9
int a, n = 5,sum = 0;

for(int i = 0; i < n; i++)
{
	cin>>a;
	sum += a;
}

float average = sum/n;
Last edited on
In C++11/14, a return statement is not required in main.

In the for loop where you receive a new value for b from the standard input on each iteration, you actually replace the previous value with the new value given by cin which may come as a surprise.

You're not adding the new value to b, you're completely obliterating the previous value of b and then you assign a new value as specified by your input.

When the for loop finally terminates 5 iterations later, the value of b is the last value provided by the standard input. So if the input is

1: 0
2: 1
3: 1
4: 2
5: 3

the value of b will be 3.

Since average is an integer, the result of b/5 will be truncated to the first integral digit. i.e, if b is 12, the result will not be 2,4 but 2.

To fix this you should change average's type to double.

Now you have enough information to solve it by yourself.
Last edited on
I did it thanksssss
Topic archived. No new replies allowed.