My objective here is to take (3) students, give each of them (3) grades, then the average of those grades for each student along with the letter grade. This part works well. The final part I need is taking those (3) average grades, adding them, then taking another average which will be the class grade average.
How should I go about getting the class average? Array? Switch statement? The reason I ask, is because I really have no idea. I am legitimately clueless as how I can accomplish this.
#include <iostream>
#include <ostream>
#include "stdafx.h"
using namespace std;
// start the program
int main() {
// LOCAL VARIABLES
// int student1, student2, student3; //the (3) students -- NOT EVEN SURE
// I NEED THIS
int all_students; // number of students
double grade1, grade2, grade3; // the (3) grade variable declarations
double grade_total; // holds the sum of all grades
double grade_avg; // holds the average of the sum of grades
cout << "Enter the number of students in the class: "; // number of students
// request
cin >> all_students;
all_students = 1; // initialize counter for the loop
// need to create a loop for all three students and input for 3
// grades/student
while (all_students <= 3) // start the loop for the students
{
cout << "\n\nPlease enter (3) numeric grades for student "
<< all_students << ":"; // enters the 3 grades for student
cin >> grade1 >> grade2 >>
grade3; // the grades are stored in these 3 variables
grade_total = grade1 + grade2 +
grade3; // sum is the 3 sets of graders added together
grade_avg = grade_total / 3; // avg. is the sum divided by 3
// displays the output for the student grades, grade average, and letter
// grade
cout << "Student " << all_students << " grades are \n" << grade1 << "\n"
<< grade2 << "\n" << grade3 << "\n"
<< "with an average of: " << grade_avg
<< ", which is letter grade: "; // need this line to also read the
// letter grade for the average
// grade
if (grade_avg >= 90) // 90+ gets an A
cout << "A";
else if (grade_avg >= 80) // 80-89 gets a B
cout << "B";
else if (grade_avg >= 70) // 70-79 gets a C
cout << "C";
else if (grade_avg >= 60) // 60-69 gets a D
cout << "D";
else // anything less than a 60% is an F
cout << "F";
// increases counter! Incrementer.
all_students++; // Yes, I want to increment the count after the loop.
//****************************************************************//
// I need to figure out how to create an array to hold //
// each student average in order to calculate the overall //
// class average. Or use a switch statement? Advice? //
//****************************************************************//
//****************************************************************//
//****************************************************************//
}
}
you need to create an array outside the while with maximum number of students, then inside the while loop (at the end of it) assign each calculated average to one entry in that array.
then outside the while loop, write a for loop to calculate the averge of the elements in the array, which are the averages of each student
The simplest way is to have a running average
float classAvg = 0;
const unit NUM_STUDENTS = 3;
while (all_students <= NUM_STUDENTS) //start the loop for the students
{
...
classAvg += grade_avg;
}
classAvg /= NUM_STUDENTS
cout<<"Class average is " << classAvg;
I also recommend making the part that converts numeric grade to letter grade into a function. That will make your code more modular and cleaner. Something along the lines of:
void displayLetterGrade(float grade)
{
if (grade >= 90) // 90+ gets an A
cout << "A";
else if (grade >= 80) // 80-89 gets a B
cout << "B";
else if (grade >= 70) // 70-79 gets a C
cout << "C";
else if (grade >= 60) // 60-69 gets a D
cout << "D";
else // anything less than a 60% is an F
cout << "F";
}
Related
This program will need to handle all grades for 10 students.
Each student has a first and last name, an id number,
3 homework grades, 3 labs grades, 3 test grades, and 1 final exam grade.
display the final course grade in both numbered and letter version
The equation only works for the first set of grades then it adds a little bit to the next average I just can't figure out whats wrong.
/*This program will need to handle all grades for 10 students.
Each student has a first and last name, an id number,
3 homework grades, 3 labs grades, 3 test grades, and 1 final exam grade.
display the final course grade in both numbered and letter version
*/
#include <iostream> // main library
#include <string> //enables use of strings
#include <iomanip> // for setw
#include <Windows.h> // used to set console title
using namespace std; // for cout and cin
const int MAXSTUDENTS = 2;
const int MAXGRADES = 3;
const int MINGRADES = 1;
int main()
{// Get names form students
SetConsoleTitle("Gradebook");
double hwGrade[MAXSTUDENTS][MAXGRADES];
double labGrade[MAXSTUDENTS][MAXGRADES];
double testGrade[MAXSTUDENTS][MAXGRADES];
double feGrade[MAXSTUDENTS];
double final_num_grade[MAXSTUDENTS];
double hwAve =0, labAve=0, testAve=0; // this will be used to calculate the averages
string fName[MAXSTUDENTS];
string lName[MAXSTUDENTS];
string line; // to set the two string variables
string id[MAXSTUDENTS]; // id will be a whole number so int was apropiate
//first for statement. ensuere that the program is run 10 times
for (int s = 0; s < MAXSTUDENTS; s++) {
cout << "Enter student's first name: "; // ask the user for the first name
getline(cin, fName[s]); // accepts students first name
cout << "Enter stedent's last name: "; //ask the user for last name
getline(cin, lName[s]); // accepts students last name
cout << "Enter student's id: "; // ask user for student id
getline(cin, id[s]);
// this loop will ask for three homework grades
for (int n = 0; n < MAXGRADES; n++) {
cout << "Homework grade " << n + 1 << " is "; //tells the user waht the program needs
cin >> hwGrade[s][n]; //lets the user input the homework grades
hwAve += hwGrade[s][n];
}
hwAve = hwAve / 3;
// this loop will ask for three lab grades
for (int l = 0; l < MAXGRADES; l++) {
cout << "Lab grade " << l + 1 << " is ";
cin >> labGrade[s][l]; //lets the user input the LAB grades
labAve += labGrade[s][l];
}
labAve = labAve / 3;
//this loop will ask for three test grades
for (int t = 0; t < MAXGRADES; t++) {
cout << "Test grade " << t + 1 << " is ";
cin >> testGrade[s][t]; //lets the user input the test grades
testAve += testGrade[s][t]; // the average is calculated
}
testAve = testAve / 3;
cout << "Final exam grade: "; // asks user for final exam grade
cin >> feGrade[s];
// equation to get the final course grade
final_num_grade[s] = (hwAve * 0.20) + (labAve * 0.25) + (testAve * 0.30) + (feGrade[s] * 0.25);
line.assign(50, '-');
cout << line << endl;
}
for (int i = 0; i < MAXSTUDENTS; i++) {
cout << "Final Course Grade for " << fName[i] << " " << lName[i] << " with the id " << id[i] << " is " // displays name of student
<< showpoint << fixed << setprecision(1) << final_num_grade[i]; //set to 1 decimal place
//if statement shows the letter grade
if (final_num_grade[i] >= 89.5) { //A if student made 89.5 or more
cout << " (A)\n";
}
else if (final_num_grade[i] >= 79.5) { //B if student made 79.5 to 89.4
cout << " (B)\n";
}
else if (final_num_grade[i] >= 69.5) { // C if student made 69.5 yo 79.4
cout << " (C)\n";
}
else if (final_num_grade[i] >= 59.5) { // D if student made 59.5 to 69.4
cout << " (D)\n";
}
else { // F if student made less than 59.4
cout << " (F)\n";
}
}
return 0;
}
You haven't reset these variables to zero : hwAve, labAve, testAve which makes the second student's grade will be slightly higher
#include <iostream>
using namespace std;
int main()
{
int score;
int numTests;
int total = 0; //why total has to be set to 0
double average;
cout << "How many tests: ";
cin >> numTests;
int s = 1;
while (s <= numTests)
{
cout << "Enter score # " << s << ": "; // why put the s there ???
cin >> score;
total += score;
s++; //why update the counter
}
cout << "total" << total << endl;
average = (double)total / numTests;
cout << "Average" << average << endl;
system("pause");
return 0;
}
1.My question is that why does the integer total has to be put as value 0? (int total = 0)
2.on the line that I enter the score number why do I have to input the counter s on it? (cout << "Enter score # " << s <<)
3.and why do I have the update the counter (s++)?
Question 1. in c++ and c when you defined a variable the default of value is anything from memory and its not null or 0
Question 2. cout<< is for print data and when you write cout<
Question 3. s++ mean s=s+1; and this is for the loop end while (s <= numTests)
Before you start counting the scores from the tests, naturally the total number is 0.
You put the counter s to indicate which score should be entered, i.e. "score 1", "score 2", etc... It is there for clarification of the user. Imagine you are on the other side and want to see your average from 20 tests, but each time it just shows: "Enter score:" - first, you will not be sure it works, second, at some point you might become distracted and forget how many scores you have entered. So this shows you exactly where you are at.
s++ means each time the counter increases with 1. So, when it reaches the number of tests, the loop will not continue. The counter is used as a condition for the while loop - so that the cycle will stop and not go inifinitely.
I am writing a GPA calculator program, and I want to change the value for a char to a different number.
For example if a user enters the letter a or A the value will be 4. This is what my program looks like. I know how to make it work if I use a switch cases, but I would like to do it this way.
char userInput;
char A, a = 4; // i want to change the value of A, a to 4
char B, b = 3; // i want to change the value of B, b to 3
char C, c = 2; // i want to change the value of C, c to 2
char D, d = 1; // i want to change the value of D, d to 1
char F, f = 0; // i want to change the value of F, f to 0
int count2 = 0;
int count3 = 0;
double gpa;
// the for loop is to make sure program will only run 3 times
for (int i=1; i<4;i++)
{
cout << "Test #" << i << ":" << endl;
cout << endl;
// the do while loop is being used to ensure that the user gets to
// input at least once.
do
{
cout << "Enter a Letter Grade (enter 'X' to exit): ";
cin >> userInput;
// the while loop is only being used for input valiation.
while (userInput!='A' && userInput!='a' && userInput!='B' &&
userInput!='b' && userInput!='C' && userInput!='c' &&
userInput!='D' && userInput!='d' && userInput!='F' &&
userInput!='f' && userInput !='X' && userInput !='x')
{
cout << "\n Invalid letter grade, please try again.\n";
cout << "\n Enter Letter Grade (enter 'X' to exit):";
cin >> userInput;
}
//line number 80 will add the values of the userInput together.
count2+=userInput;
// line 83 is a counter that holds the number of times the loop
// as excuted
count3++;
// line 88 will get a grade point average by dividing count3
// by count2
cout << fixed << showpoint << setprecision(2);
gpa = count2/count3;
} while(userInput !='X' && userInput!='x');
cout << "Total Grade Point: " << count2 << endl;
cout << "GPA: " << gpa << endl;
}
If my question is too vague please let me know so I can clarify.
If you look at ASCII table, you'll see that letters are just numbers.
http://www.asciitable.com/
You can calculate offset using simple subtraction:
'a' - 'a' == 0
'b' - 'a' == 1
'c' - 'a' == 2
and so on. To convert it to GPA grade you can do a simple conversion:
int deltaA = (int)('a' - 'a'); // explicit cast to int is not really needed
int max = 4;
int grade = max - deltaA;
Alternative solution would be to use a map:
std::map<char, int> grades;
grades['a'] = 4;
grades['b'] = 3;
grades['c'] = 2;
...
int score = grades['a']; // score == 4
It would be a good idea to stick with upper or lowercase letters. You can convert them using int std::tolower(int ch) and int std::toupper(int ch) functions. Putting char into int is ok - both are integers and int has wider range and char will fit.
The other way around - not so easy. int has wider range than char and you should check if your int value is in char range before converting back.
A couple of things...
char A, a = 4;
Creates character VARIABLES (storage locations) and assigns the variable a the value of 4. A variable represents a memory location, a place to store information. It is a human readable representation of this storage location. It is not a translation mechanism. The CHARACTER 'a' is a value represented by an ascii code that can be stored in the variable, hex value is 61 or decimal 97. Variable a is not the same thing as the character value 'a'. and storing a decimal 4 into a character variable is setting it to the EOT character.
Your best bet is to use the switch. It works fine.
It's best practice to initialize variables before you use them. Your counters will probably start out as zero, but depending on compilers, they may contain random values. Set them to zero before entering your loops.
Thank you guys for all the help. This is how I solved my problem. I meant to post it a while ago but just forgot.
char userInput;
// the for loop is to make sure program will only run 3 times
for (int i=1; i<4;i++)
{
int count2 = 0;
double count3 = 0.0;
double gpa;
cout << "Test #" << i << ":" << endl;
cout << endl;
// the do while loop is being used to ensure that the user gets to
// input at least once.
do
{
cout << "Enter a Letter Grade (enter 'X' to exit): ";
cin >> userInput;
// the while loop is only being used for input validation.
while (userInput!='A' && userInput!='a' && userInput!='B' &&
userInput!='b' && userInput!='C' && userInput!='c' &&
userInput!='D' && userInput!='d' && userInput!='F' &&
userInput!='f' && userInput !='X' && userInput !='x')
{
cout << "\n Invalid letter grade, please try again.\n";
cout << "\n Enter Letter Grade (enter 'X' to exit):";
cin >> userInput;
}
if(userInput !='X' && userInput !='x')
{
int grade=func(userInput);
// count2 will add the values of the userInput together
count2+=grade;
// count3 is a counter that holds the number of times the loop
// as execute.
count3++;
}
cout << fixed << showpoint << setprecision(2);
// to get the grade point avarage you need to divide count3 by count2
gpa = count3/count2;
} while(userInput !='X' && userInput!='x');
// the next few lines will display the information gathered
cout << endl;
cout << "Total Grade Points: " << count2 << endl;
cout << "GPA: " << gpa << endl;
cout << endl;
cout << endl;
}
return 0;
}
int func(char userInput)
{
// grade is being set to zero so there is a less chance of getting wrong
// data
int grade=0;
// this will make the userInput into a capital letter
userInput=toupper(userInput);
// we are setting value to equal the ascii number of the chosen
// letter
int value=userInput; // if input='A' then value = 65
// by subtracting 69 by the value it will help get us the point value
// we need.
grade=69-value; // gpa=4
// if the number value of grade becomes negative it will assign grade
// to store the number 0
if(grade<0)grade=0;
return grade;
}
This program will play a game with the user, called Odds and Evens. The computer will play Evens, and the human user will play Odds. For a round of the game, each player picks an integer in the range [1,10]. The players pick their numbers independently: neither player knows the other player's number before choosing its own number. If the sum of the numbers is even, then Evens (the computer) wins that round; if the sum of the numbers is odd, then Odds (the human) wins that round. The game continues for as many rounds as the user want to play; the user ends the game by typing a non-# or a number outside [1,10] for the input. At the end of the game, the program summarizes the score.
I am having trouble properly looping this question. Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number. Also i do not know how I would have the program summarize the score. Help would be much appreciated as I have another problem for homework that is similar to this!
Here is my code:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;
bool die(const string & msg);
int main(){
srand(static_cast<unsigned>(time(0)));
unsigned num1 = 0, num = 0, sum = 0;
bool userTurn = true;
cout << "Welcome to the Odds and Evens game!";
num = rand() % 10 + 1;
while (num){
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!";
}
else {
cout << " You win!";
}
}
userTurn = !userTurn;
}
}
bool die(const string & msg){
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number.
You don't have code to re-set the value of num when it's the computer's turn.
After the line
userTurn = !userTurn;
add
if ( !userTurn )
{
num = rand() % 10 + 1;
}
Also i do not know how I would have the program summarize the score.
Keep two counters that indicate how many times the human won and how many times the computer won.
int computerWinCount = 0;
int humanWinCount = 0;
and then, update the loop to use:
if (sum % 2 == 0){
cout << " I win!";
++computerWinCount;
}
else {
cout << " You win!";
++humanWinCount;
}
The conditional of the while loop is such that your program will never terminate. Update it to something like below.
while (true) {
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
// If the user entered a number that is not
// within range or the user did not input a number,
// then break out of the loop.
if ( !cin || num1 < 1 || num1 > 10 )
{
break;
}
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!" << endl;
++computerWinCount;
}
else {
cout << " You win!" << endl;
++humanWinCount;
}
}
userTurn = !userTurn;
if ( !userTurn )
{
num = rand() % 10 + 1;
}
}
To report the summary, add the following lines before the end of the main.
cout << "Number of times I won: " << computerWinCount << endl;
cout << "Number of times you won: " << humanWinCount << endl;
Here:
num = rand() % 10 + 1;
while (num){
... // never change num
}
Do you see the problem? The computer player chooses num randomly, but only once. Just put another num = rand() % 10 + 1; inside the main loop.
(Also, you don't seem to have a way for the user to terminate the game.)
So you want a simple loop that will do the following things.
get the user input.
get the computer input
check to see who win's the current round
update scores.
this happens until the user chooses an option not from 1 to 10
after this you want to display the score.
Here is a complete example.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
int mynum, compNum, myScore(0), compScore(0);
srand(time(NULL));
cout << "Welcome to the Odds and Evens game!" << endl;
cout << "Your # in [1,10] is ";
while ((cin >> mynum) && mynum > 0 && mynum <= 10){
compNum = rand()%10 + 1;
if ((mynum + compNum)%2){
cout << "You win" << endl;
++myScore;
} else {
cout << "Computer Wins" << endl;
++compScore;
}
cout << "Your # in [1,10] is ";
}
cout << "You won " << myScore << " games" << endl;
cout << "The computer won " << compScore << " games" << endl;
return 0;
}
Your problem with the computer's number not changing is due to the fact you do not update its value within the loop.
If you want to keep track of the score, you can simply keep two integers that keep track of how many times the user has won and how many times the computer has won. Then at the end (after the while loop) cout each of their scores.
Overall your code is pretty close.
You just need to make sure you update the computer's guess inside the while loop and when you decide who's won the round increment that person's score.
The whole loop condition in your original code will always evaluate to true. As num will always be to a number 1 to 10. You'll want to use the user's input in the while loop condition.
The while condition in my code will do the following:
get the user's input. cin >> mynum will evaluate to false if cin fails to read a number. If it did read a number the condition will check to see if the number is between 1 and 10 inclusive.
I am new to C++ and programming in general so this is all difficult for me but I am really trying to learn. I can't get the letterGrade function to display correctly. I gives me the letter grade like it should but also adds a bunch of numbers after the letter grade. Could anyone please let me know what is going on and what I am doing wrong? Also I am supposed to use a function to find the average but I can only make it work by defining a variable sAverage in my "for" loop to display the array like a table. I had created a function for that as well but it didn't give me the right answer. Here is my code.
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int letterGrade(int average)
{
if (average > 89)
cout << "A";
else if (average > 79 && average < 90)
cout << "B";
else if (average > 69 && average < 80)
cout << "C";
else if (average > 59 && average < 70)
cout << "D";
else if (average >= 0 && average < 60)
cout << "F";
}
void getInfo()
{
const int info = 2;
string last[info];
string first[info];
int ID[info];
int score1[info];
int score2[info];
int score3[info];
for (int count = 0; count < info; count++)
{
cout << "last name\n";
cin >> last[count];
cout << "first name\n";
cin >> first[count];
cout << "enter ID\n";
cin >> ID[count];
cout << "enter test 1\n";
cin >> score1[count];
cout << "enter test 2\n";
cin >> score2[count];
cout << "enter test 3\n";
cin >> score3[count];
}
cout << endl;
cout << "Last Name\tFirst Name\tID\tTest 1\tTest 2\tTest 3\tAverage\t Grade\n";
cout << "__________________________________________________________________\n";
for (int count = 0; count < info; count++)
{
int sAverage = ((score1[count]+score2[count]+score3[count])/3);
cout << setw(10) << last[count]
<< setw(10) << first[count]
<< setw(10) << ID[count]
<< setw(10) << score1[count]
<< setw(10) << score2[count]
<< setw(10) << score3[count]
<< setw(10) << sAverage
<< setw(10) << letterGrade(sAverage);
cout << endl;
}
}
int main(int argc, char *argv[])
{
cout << "Enter Student Info\n";
getInfo();
system("PAUSE");
return EXIT_SUCCESS;
}
The function I had to find the average was:
int getAverage(score1, score2, score3)
{
int average;
average = ((score1 + score2 + score3) / 3);
return average;
}
I called it like this
cout << getAverage(score1[info],score2[info],score3[info])
but it only came back with a high number in the hundreds but what I need is a function do average the scores in the array from the input.
Thanks in advance and again I am new to all this.
When you call the function:
cout << getAverage(score1[info],score2[info],score3[info])
where info is equal to 2, you're accessing memory out of bounds of the array. You're length of an array is 2, so the only valid indices are 0,1 - not 2.
Moreover, in the definition of function:
int getAverage(score1, score2, score3)
{
int average;
average = ((score1 + score2 + score3) / 3);
return average;
}
You didn't specify the types of scoreX variables, and the the implicit int rule is not valid in C++.
EDIT:
Another thing: when you're calculating the average, you have to remember that dividing an integer by an integer always gives an integer, so if you want to have more precise answer, e.g. for 2.66 2 3 3, you have to use a float.
Maybe you mis-read your output? The getAverage function should work correctly even though you didn't specify types for the parameters (they default to int, then).
It looks like your problem is a different one: your function letterGrade doesn't have a return statement, so it returns random junk. Your compiler should actually warn you about that. This junk is interpreted as a number (since you said the function is returning int) and formatted that way.
What you probably want is something like:
string letterGrade(int average)
{
if (average > 89)
return "A";
else if (average > 79 && average < 90)
return "B";
else if (average > 69 && average < 80)
return "C";
else if (average > 59 && average < 70)
return "D";
else if (average >= 0 && average < 60)
return "F";
else
return "-"; // negative value was passed!
}
You use << within a function without flushing cout. In fact, you say in the letterGrade prototype that you return an int but you don't, so when you call something like cout << letterGrade(...), it prints a random number
The protoype of letterGrade should rather be :
string letterGrade(int average)
and you must return your letter (using for example return "F"; instead of cout << "F").
It is often bad idea to print on the standard output without endl nor cout.fflush().