c++ average help

Discussion in 'Software Development' started by supergoten, Apr 14, 2009.

Not open for further replies.

Joined:
Apr 14, 2009
Messages:
28
I'm trying to make a program to calculate the average of grades, can anyone please explain what I'm doing wrong?

#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int x,y;
int *p;
int total=0;
int average= total / x;

cout << "Please insert the number of scores "<<endl;
cin >> x;
p= new int[x];
for (y=0; y<x; y++)
{
cout << "Please enter a score: "<<endl;
cin >> p[y];
}
cout << "The scores are: ";
for (y=0; y<x; y++)
cout << p[y] << ", ";
cout<<"The average is: ";
for (int y=0; y<x; y++)
{
total += p[y];
}
delete[] p;
system("pause");
return 0;
}

2. middersAccount Closed

Joined:
Dec 31, 1969
Messages:
645
I'm more of a C man, than C++, but from a glance I would say that your definition of the average variable appears before x is assigned a value and so will be NULL. You should split it into two lines:
int average; (although 'float average' would be more appropriate)
...
average = total/x; // after total and x have been set/calculated

Sláinte

midders
P.S. I'd also strongly advise you to start using indentation/tabs to format your code (to indicate the contents of loops etc.) and a sprinkling of comments; this is a fairly short prog, but they'll quickly get longer.

Joined:
Apr 14, 2009
Messages:
28
well then would this be more accurate?

#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int x,y;
int *p;
int total=0;
int average;

cout << "Please insert the number of scores "<<endl;
cin >> x;
p= new int[x];
for (y=0; y<x; y++)
{
cout << "Please enter a score: "<<endl;
cin >> p[y];
}
cout << "The scores are: ";
for (y=0; y<x; y++)
cout << p[y] << ", ";
cout<<"The average is: ";
for (int y=0; y<x; y++)
{
total += p[y];
average= total / x;
}
delete[] p;
system("pause");
return 0;
}

i've been using C++ for a little bit but i'm still a beginner, and this one has stumped me!

And sorry about the poor formatting, i copied it over on a different computer without Dev C++ and so the Text editor messed it up.

4. middersAccount Closed

Joined:
Dec 31, 1969
Messages:
645
There's no need to calculate the average at every iteration of the loop, just once at the end:
Code:
```for (y=0; y<x; y++) total += p[y];
average= total / x;
```
Sláinte

midders

Joined:
Apr 14, 2009
Messages:
28
Thank you so much, it's working now! I'm a grateful C++ newbie.

As Seen On