Error Displayed While Printing variable
I wish I knew were the error in this was, but I do not. Here is the class:
class Student
{
public:
float grade[10];
float averageGrade;
float average();
Student() : averageGrade(0.0f) {}
};
Here is the function:
float Student::average()
{
cout << "How many grades would you like to enter? (Up to ten)\n";
float x;
cin >> x;
cout << "What is your first grade?";
cin >> grade[0];
for (int i = 1; i < x; i++)
{
cout << "What is the next number?\n";
cin >> grade[i];
}
averageGrade = accumulate(grade, grade+10, 0.0);
averageGrade = averageGrade / x;
return averageGrade;
}
And here is main:
int main()
{
Student s;
s.average();
cout << s.averageGrade;
system ("PAUSE");
return 0;
}
So whenever it outputs s.averageGrade, I just get what looks like a memory address or something. There are no errors when compiling.
Here is the output:
1>------ Build started: Project: Weapons, Configuration: Debug Win32 ------
1>Compiling...
1>weapon.cpp
1>c:\users\hastudent\documents\visual studio 2008\projects\weapons\weapons\weapon.cpp(31) : warning C4244: '=' :开发者_开发百科 conversion from 'double' to 'float', possible loss of data
1>Linking...
1>Embedding manifest...
1>Build log was saved at "file://c:\Users\HAStudent\Documents\Visual Studio 2008\Projects\Weapons\Weapons\Debug\BuildLog.htm"
1>Weapons - 0 error(s), 1 warning(s)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
One problem is that you pass grade+10
to accumulate, even if the user does not enter ten records. This may cause accumulate to read junk data, which can have unpredictable effects.
You can fix this by changing x from a float to an int, and changing the accumulate call to averageGrade = accumulate(grade, grade + x, 0.0);
You're printing out the averageGrade
member that you never assigned so it has a random value. You want to print the output of the function instead: std::cout << s.average()
You are adding 10
numbers even if the user specified less than 10
.
averageGrade = accumulate(grade, grade+10, 0.0);
This line should be
averageGrade = accumulate(grade, grade+x, 0.0);
The grade[10] values do not automatically get initialize to 0.0
.
精彩评论