c++ gpa calculator not accepting grade input - c++

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int course, numberOfClasses; //declare variables
double gradePointTotal = 0, gradePointAve; //initialize to 0
string grade;
cout << "GPA Calculator \n";
cout << "\n Enter the number of classes ";
cin >> numberOfClasses; // enter number of classes
for (course = 1; course <= numberOfClasses; course++ ) // define loop
{
cout << "\n Enter a letter grade for class number " << course << ": ";
cin >> grade; //Enter grade
if ( grade == "A" || grade == "a") //accepts upper and lower case
gradePointTotal = gradePointTotal + 4;
else if ( grade == "B" || grade == "b")
gradePointTotal = gradePointTotal + 3;
else if ( grade == "C" || grade == "c")
gradePointTotal = gradePointTotal + 2;
else if ( grade == "D" || grade == "d")
gradePointTotal = gradePointTotal + 1;
else if ( grade == "F" || grade == "f")
gradePointTotal = gradePointTotal + 0;
gradePointAve = gradePointTotal / numberOfClasses; // calculate the GPA
cout << "\n Your GPA is: " << gradePointAve << endl; // display GPA
}
}
I'm a newb to C++. I am not exactly sure why...but my output is not correct. This program calculates gpa. I am able to enter the number of classes I am using, however-I can not enter the letter grades. I was getting an error with my line:
cin >> grade;
but I was able to fix the error message by adding #include . However, it is not doing what is expected....
Why can I not enter my letter grades when the console screen pops up?

gradePointAve = gradePointTotal / numberOfClasses; // wrong
is wrong, since you would imply that gradePointTotal contains all grades. but since you are looping, that's not the case.
You need to set course, not numberOfClasses as the quotient:
gradePointAve = gradePointTotal / course; // correct
at least that gives you the correct result.
And remove #include "stdafx.h", you don't need that. It's not really nice to have standard libraries in your project folder. And again, you don't need it for the code.

Related

GPA rater in C++

I'm trying to code a GPA rater.
The problem:
Write a C++ program that asks the user for their cumulative GPA in the range [0,4]. If the GPAenter code here
is in:
[3-4] you say, “Superb!”
[2-3[ you say, “Good!”
[1-2[ you say, “Hmm!”
[0-1[ you say, “No comment!”
The program should display an error message and exit if the GPA entered exceeds 4 or less than
0.
Code:
#include <iostream>
using namespace std;
int main()
{
double grade;
cout << "Input your GPA: ";
cin >> grade;
cout << endl << endl;
if (grade >= 0 && grade <= 4)
{
if (grade >= 0 && grade <= 1)
{
cout << "No comment!";
}
if (grade >= 1 && grade <= 2)
{
cout << "Hmm!";
}
if (grade >= 2 && grade <= 3)
{
cout << "Good!";
}
if (grade >= 3 && grade <= 4)
{
cout << "Superb!";
}
}
else
{
cout << "Error : GPA is not in the specified range";
}
return 0;
}
I feel there is a more efficient way than mine.
Is there?
Thanks in advance
There's probably a way to code golf it, but your code is clear. It does check things that you already know more than once.
For example, if (grade >= 0), then it still is on the next line. If it's not <= 1, then it is definitely > 1 -- you only need to check if it's <= 2 (with else if).
If you want to make something silly, you could something like this (after checking if grade is in range):
string m[4] = {"No comment!", "Hmm!", "Good!", "Superb!"};
cout << m[min(3, int(grade))];
You need to add:
#include <cmath>
#include <string>
It's fewer lines of code, but possibly not more efficient (you need to measure)

Need help defining a Loop Control Variable (while loops) C++

I have been trying forever to figure out what loop control variable (LCV) to use for my program to work but I have been unsuccessful.
The information given is as follows:
You will be promoting a student for grades and credits for courses taken. From that, you will calculate a GPA.
The course name is prompted for, but nothing is done with it.
We are just using the grades A, B, C, D, and F so you won't have to do so much typing!
You will need to use the "set precision" command as shown in the book. Set it to "fixed" and "2".
You will need to use the "cin.ignore()" function as discussed earlier in the course.
Notes
I used int total to count the number of classes.
Current while statement was my last attempt, and it is not correct.
My code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main () {
cout << std::fixed << std::setprecision(2);
string course, grade, answer;
int credits, total = 0;
float gradePoints = 0, totalCredits = 0;
float gpa = 0.0;
while (grade <= "ABC") {
cout << "Enter a course name: ";
getline(cin, course);
cout << course << endl;
cout << "Enter number of credits: ";
cin >> credits;
cout << credits << endl;
cout << "Enter your grade (A, B, C, D, F): ";
cin >> grade;
cout << grade << endl;
cout << "Continue ('Yes' or 'No')? ";
cin >> answer;
cout << answer << endl;
if (grade == "A") {
gradePoints = gradePoints + 4;
}
else if (grade == "B") {
gradePoints == gradePoints + 3;
}
else if (grade == "C") {
gradePoints = gradePoints + 2;
}
else if (grade == "D") {
gradePoints = gradePoints + 1;
}
else if (grade == "F") {
gradePoints = 0;
}
total = total + 1;
totalCredits = totalCredits + credits;
}
gpa = (total * gradePoints)/ totalCredits;
return 0;
}
Based on the way the rest of the program is written, I'd think that you'd want to check against the user's response to the "Continue?" question. Something like this:
bool answer = true;
while (answer) {
// code
// when ready to exit...
answer = false;
}
That said, it might make more sense to use a do-while loop, where the first block executes before the conditional is checked:
do {
// code
} while (answer != "No");
And while you're at it, you might also want to consider using a different flag than having the user type in "Yes" or "No". Something like y and n is more common and a bit simpler.
"while (grade <= "ABC")"
If the intent is to say only do the loop while grade has a value of A, or B, or C, then:
while(grade == "A" || grade == "B" || grade == "C")

Looping assignment in C++

My assignment is utilizing loops. The program should accept input for the sales of 3 employees (Mary, Tom, and Chris). The flow should be as follows:
Initial? > number of sales to enter > enter sale amounts > display commission for sale at 17% > adds commission and sales to the respective variables >> continue until 'z' is input for inputSalesPerson >> display information
So I am trying to figure out why my return value for the tempComm variable isn't returning the correct value. If i was to enter 't' for variable inputSalesPerson it puts me into the switch case 't' no problem. Input number of sales and that works. But when I get to entering the salesAmount and then displaying commission it will not calculate correctly.
Also if I enter 'z' or 'Z' as the inputSalesPerson it will not end the program. I have a lot to go on this.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int salesT = 0, salesC = 0, salesM = 0;
double amountT = 0, amountC = 0, amountM = 0;
double commT = 0, commC = 0, commM = 0;
double commRate = (17/100);
int num_sales;
double salesAmount, totalSales, tempComm;
char inputSalesPerson;
do
{
cout << "Enter the sales person's initial (\"Z\" to quit): ";
cin >> inputSalesPerson;
while(inputSalesPerson != 't' && inputSalesPerson != 'T' && inputSalesPerson != 'm' && inputSalesPerson != 'M' && inputSalesPerson != 'c' && inputSalesPerson != 'C' && inputSalesPerson != 'z' && inputSalesPerson != 'Z')
{
cin.get();
system("cls");
cout << "Invalid input for employee. Please Input (T)om, (C)hris, (M)ary, or (Z) to End : ";
cin >> inputSalesPerson;
}
switch(inputSalesPerson)
{
case 't' :
case 'T' :
system("cls");
cout << "Enter the number of sales : ";
cin >> num_sales;
while(num_sales < 1 || num_sales > 5)
{
system("cls");
cout << "Invalid number of sales. Please enter a value between 1 and 5 : ";
cin >> num_sales;
}
salesT += num_sales;
for(int i = 0; i<num_sales; i++)
{
cin.get();
system("cls");
cout << "Enter the sale amount : ";
cin >> salesAmount;
while(salesAmount < 0)
{
cin.get();
system("cls");
cout << "Invalid sale amount. Please enter a positive amount : ";
cin >> salesAmount;
}
tempComm = salesAmount + (salesAmount * commRate);
cout << fixed << setprecision(2) << "Commission earned by tom on this sale is : " << tempComm << endl;
cin.get();
amountT += salesAmount + tempComm;
commT += tempComm;
totalSales += amountT;
}
break;
}
}while(inputSalesPerson != 'z' || 'Z');
return 0;
}
****EDIT****
Thank you for the information on single-step debugging. Thanks to that comment I was able to learn about using the debugging tool more in depth and that helped me get everything working a bit better.
I've commented your code at the areas that need fixing. Also, there's a problem with using cin.get() all over the place. I assume that you do this to discard the return character after each input. But if the standard input (cin) is empty when you call cin.get() it will block the program until something is input. This is what happens when you enter more than one num_sales:
for (int i = 0; i<num_sales; i++)
{
cin.get();
It handles the first fine, but on the second loop you get:
Enter the sale amount : 20
Commission earned by tom on this sale is : 23.40
// cin.get() blocks here, with no user instructions to enter the next sale amount
I've commented out all the cin.get(). It will still work the same because the cin operator >> discards whitespaces and newlines, so even if there is a \n newline character still in the buffer, the next time you do something like cin >> num_sales it will discard the newline anyway.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int salesT = 0, salesC = 0, salesM = 0;
double amountT = 0, amountC = 0, amountM = 0;
double commT = 0, commC = 0, commM = 0;
double commRate = (17 / 100.0); // Int divided by int will round to an int.
// commRate is 0.0. Divide by double instead (17 / 100.0)
int num_sales;
double salesAmount, totalSales = 0, tempComm; // totalSales needs to be initialised to
// zero, otherwise it holds a garbage value.
char inputSalesPerson;
do
{
cout << "Enter the sales person's initial (\"Z\" to quit): ";
cin >> inputSalesPerson;
while (inputSalesPerson != 't' && inputSalesPerson != 'T' && inputSalesPerson != 'm' && inputSalesPerson != 'M' && inputSalesPerson != 'c' && inputSalesPerson != 'C' && inputSalesPerson != 'z' && inputSalesPerson != 'Z')
{
//cin.get();
system("cls");
cout << "Invalid input for employee. Please Input (T)om, (C)hris, (M)ary, or (Z) to End : ";
cin >> inputSalesPerson;
}
switch (inputSalesPerson)
{
case 't':
case 'T':
system("cls");
cout << "Enter the number of sales : ";
cin >> num_sales;
while (num_sales < 1 || num_sales > 5)
{
system("cls");
cout << "Invalid number of sales. Please enter a value between 1 and 5 : ";
cin >> num_sales;
}
salesT += num_sales;
for (int i = 0; i<num_sales; i++)
{
//cin.get();
//system("cls");
cout << "Enter the amount for sale number " << i+1 << ": ";
cin >> salesAmount;
system("cls"); // I would put the clear here,
// Otherwise the user can't see the commission made by Tom
while (salesAmount < 0)
{
//cin.get();
system("cls");
cout << "Invalid sale amount. Please enter a positive amount : ";
cin >> salesAmount;
}
tempComm = salesAmount + (salesAmount * commRate);
cout << fixed << setprecision(2) << "Commission earned by tom on this sale is : " << tempComm << endl;
//cin.get();
amountT += salesAmount + tempComm;
commT += tempComm;
totalSales += amountT; // I think you mean to add salesAmount maybe?
}
break;
}
} //while (inputSalesPerson != 'z' || 'Z');
// Even if { this ^^^^} is false, ^^^ this is always
// 'Z' char will convert to bool, any non-zero value is true.
while (inputSalesPerson != 'z' && inputSalesPerson != 'Z');
return 0;
}

C++ | An array, switch statement? Need some guidance

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";
}

How do I stop a certain part of a program using the user's input?

I'm making a program that tallies grades. I want to know how to stop a certain part of a program based on the user's input. Below is the program I am working on. How do I stop the program if the user enters "done"? Also, I don't necessarily have to use "done" to exit the program. I was initially going to use -1, but I ran into a problem where I had to make a robust program where values < 0 and > 100 are not accepted.
int grade;
a=b=c=d=f=0;
do
{
cout << "Enter a grade or enter done to stop. ";
if (grade >= 90 && grade <= 100)
{a++;}
if (grade >= 80 && grade < 90)
{b++;}
if (grade >= 70 && grade < 80)
{c++;}
if (grade >= 60 && grade < 70)
{d++;}
if (grade >= 0 && grade < 60)
{f++;}
} while (grade != 'done');
just do a return 0? Also, you can't do grade = 'done', unless you overrode the = operator or something.
The most simple way to ask user to enter integer value, which is out of range of values you expected him to enter (ex. -1). "when done - enter -1".
Also if(grade = 'done') - assignement is here, to compare use operator==, which is
// if(grade == 'done')
or you can use the following approach:
do
{
cout << "Enter a grade or enter done to stop. ";
// first try to get string from user (which he/she enters when done)
string str;
cin >> str;
if (str == "done") // if done was entered - exit from the loop
break;
// else clear fail bit in stream object and read int value
cin.clear();
cin >> grade;
if (grade >= 90 && grade <= 100)
{//a++;}
if (grade >= 80 && grade < 90)
{//b++;}
if (grade >= 70 && grade < 80)
{//c++;}
if (grade >= 60 && grade < 70)
{//d++;}
if (grade >= 0 && grade < 60)
{//f++;}
} while (grade != 'done');
Firstly, "grade" is type int, so you can not convert int to *char, if you want that "grade" is int than you can exit with -1. Or if you want to exit with "done", than grade can be char[5], and you can use atoi() to convert string to integer to check, and strcmp() to compere "grade" with "done".
You have write code to enter a string. You can then test if the string equals "done". If it doesn't you then convert the string to an integer, then you can check against your grade boundaries.
If you really want to use numbers AND strings i suggest using stringstreams. Here is an example:
string Text = "456";//string containing the number
int Result;//number which will contain the result
stringstream convert(Text); // stringstream used for the conversion initialized with the contents of Text
if ( !(convert >> Result) )//give the value to Result using the characters in the string
Result = 0;//if that fails set Result to 0
//Result now equal to 456
Source link
First of all, single quotes denote a character literal, double quotes a null terminated string (2.14 or so).
if(grade = 'done') will always be true, compiler should have thrown a warning at you that you aren't doing what you think you are doing, you're assigning it then checking if it is true, which it will always be.
And you're trying to assign an integer to a string.
This seems like homework so i won't write it, but you need to take in a string from stdin, then parse it, e.g is it an integer or string, the act on that data. to terminate you can call exit, break from the loop or return from the function.
You can take the inputs as string, if the first character is not a digit then break the loop, covert the string to integer otherwise:
#include<iostream>
#include<string>
#include<cctype>
#include<cstdlib>
using namespace std;
int main() {
int grade;
string input;
int a, b, c, d, f;
a=b=c=d=f=0;
do
{
cout << "Enter a grade or enter done to stop: ";
cin >> input;
cout << endl;
if(!isdigit(input[0])) {
break;
} else {
grade = atoi(input.c_str());
}
if (grade >= 90 && grade <= 100)
{a++;}
if (grade >= 80 && grade < 90)
{b++;}
if (grade >= 70 && grade < 80)
{c++;}
if (grade >= 60 && grade < 70)
{d++;}
if (grade >= 0 && grade < 60)
{f++;}
} while (1==1);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "d = " << d << endl;
cout << "f = " << f << endl;
getchar();
return 0;
}