user2977608 user2977608 - 3 months ago 10
C++ Question

Having if/else trouble while creating a C++ class

I'm having trouble with a homework assignment.

Everything works as expected except for the

letter_grade
part. I'm not getting any compile errors, but every time I run the program, the
letter_grade
is -858993460. I know it's probably something simple that I am overlooking, but I've hit a wall and am pretty much out of ideas.

#include <iostream>
#include <string>
using namespace std;

// Class Declaration

class StudentRecord
{
string id;
int A, B, C, D, F, grade;
float avg, exam1, exam2;

public:
void input();
void output();
void average();
void letter_grade();
};

// Gathering data

void StudentRecord::input()
{

cout << " Please enter your student ID: ";
cin >> id;
cout << "\n";
cout << " Enter your score for exam 1: ";
cin >> exam1;
cout << "\n";
cout << " Enter your score for exam 2: ";
cin >> exam2;
}

// Calculations

void StudentRecord::average()
{
avg = (exam1 + exam2) / 2;
}

void StudentRecord::letter_grade()
{
if ((avg >= 90) && (avg <= 100))
grade = A;
else if ((avg >= 80) && (avg < 90))
grade = B;
else if ((avg >= 70) && (avg < 80))
grade = C;
else if ((avg >= 60) && (avg < 70))
grade = D;
else (avg < 60);
grade = F;
}

// Output Data

void StudentRecord::output()
{
cout << "\n\n";
cout << " *** Student Record ***" << endl;
cout << "\n";
cout << " Student ID: " << id << endl;
cout << "\n";
cout << " Grade for exam 1: " << exam1 << endl;
cout << "\n";
cout << " Grade for exam 2: " << exam2 << endl;
cout << "\n";
cout << " Average for the class: " << avg << endl;
cout << "\n";
cout << " Letter grade for the class: " << grade << endl;
cout << "\n\n";
}

int main()
{
StudentRecord student;
student.input();
student.average();
student.letter_grade();
student.output();

system ("pause");
return 0;
}

Answer

You've declared integer variables named A, B, C, D, etc. That's not really what you want here. You want to declare grade as a char variable. You want to put the character 'A', 'B', etc. in that char variable.

Example:

grade = 'A';

That puts the character 'A' into the variable grade.

If you remove those variables A...F, change grade to be of type char, and then rewrite your if-else statement to assigned letters 'A', 'B', etc. to grade, that should do the trick.

Take note of those single quotes around the characters. Those tell C++ that the thing between the quotes is a character constant.