Need help defining a Loop Control Variable (while loops) C++ - 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")

Related

Program to calculate test scores [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I am writing a program to calculate the grade of 3 test scores. The lowest of the first 2 scores is dropped and added to the third test score to make the final grade. The 3 test scores cannot be higer than 50, lower than 0 and cannot be a character or string. So far, I have satisified all those requirment but I need to implement decimal grades to the program like for instance 45.5. Also to round the final grade up or down. For example if final grade is 89.5 round up to an A.
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
char getGrade(int num) {
if (num < 60)
return 'F';
if (num < 69)
return 'D';
if (num < 79)
return 'C';
if (num < 89)
return 'B';
return 'A';
}
bool isnumeric(string temp) {
for (char &chr : temp) {
if ((chr >= '0' and chr <= '9') or chr == '-')
continue;
else
return false;
}
return true;
}
int main(int argc, char const *argv[]) {
cout << "Welcome to the grade calculator.You will input three test "
"scores.\nThe highest of the first two grades and the third grade "
"will be\nadded together to determine the numeric grade average for "
"the\ncourse.Each test score has a maximum of 50 points.\n";
int arr[3];
int ctr = 0;
string temp;
int num;
while (ctr < 3) {
cout << "\nPlease enter test score " << (ctr + 1) << ": ";
label1:
cin >> temp;
if (isnumeric(temp)) {
num = atoi(temp.c_str());
if (num > 50) {
cout << "\nTest scores cannot be higher than 50, try again: ";
goto label1;
} else if (num < 0) {
cout << "\nTest scores cannot be negative, try again: ";
goto label1;
} else {
arr[ctr++] = num;
}
} else {
cout << "\nInvalid test score entered, try again: ";
goto label1;
}
}
int average = 0;
average = max(arr[0], arr[1]);
average = average + arr[2];
cout << "\nThe average for the course = " << average << "\n";
cout << "The letter grade = " << getGrade(average);
cout << "\n\n\nThank you for using this program\n";
return 0;
}
Just changed a couple of things to make it work with decimals:
1. Added chr == '.' to the isNumeric() function:
bool isnumeric(string temp) {
for (char& chr : temp) {
if ((chr >= '0' and chr <= '9') or chr == '-' or chr == '.')
continue;
else return false;
}
return true;
}
2. Changed variable types:
double arr[3]{};
int ctr = 0;
std::string temp;
double num;
3. Removed goto: (You can just use continue)
while (ctr < 3) {
std::cout << "\nPlease enter test score " << (ctr + 1) << ": ";
std::cin >> temp;
if (isnumeric(temp)) {
num = atof(temp.c_str());
if (num > 50) {
std::cout << "\nTest scores cannot be higher than 50, try again: ";
continue;
}
else if (num < 0) {
std::cout << "\nTest scores cannot be negative, try again: ";
continue;
}
else {
arr[ctr++] = num;
}
}
else {
std::cout << "\nInvalid test score entered, try again: ";
continue;
}
}
4. For rounding off, you can use std::round() as such:
double average = 0;
average = std::max(arr[0], arr[1]);
average = std::round(average + arr[2]);
You can also change your cout statements:
std::cout << "\nThe average for the course = " << average;
if (std::round(average) != average) std::cout << ", rounded off to = " << std::round(average);
std::cout << ".\nThe letter grade = " << getGrade(average);
std::cout << "\n\n\nThank you for using this program\n";
Just make all these changes and your program will successfully work with decimals.
Also, consider not using the following in your code:
using namespace std;
..as it's considered as a bad practice. For more info on why, look up to Why is using namespace std considered as a bad practice.
Edit: To accomplish your requirement, you can just change the while loop as such:
while (ctr < 3) {
if (temp.size() == 0)
{
std::cout << "\nPlease enter test score " << (ctr + 1) << ": ";
std::cin >> temp;
}
if (isnumeric(temp)) {
num = atof(temp.c_str());
if (num > 50) {
std::cout << "\nTest scores cannot be higher than 50, try again: ";
std::cin >> temp;
continue;
}
else if (num < 0) {
std::cout << "\nTest scores cannot be negative, try again: ";
std::cin >> temp;
continue;
}
else {
arr[ctr++] = num;
temp.clear();
}
}
else {
std::cout << "\nInvalid test score entered, try again: ";
std::cin >> temp;
continue;
}
}
The above code works as you said.

c++ gpa calculator not accepting grade input

#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.

Need help creating an equation in C++ to calculate total

My updated code. When I run the code it keeps outputting the prices of all the packages instead of just the one I ask for.
#include <iostream>
using namespace std;
int main() {
// to keep it simple
int choice_a = 995;
int choice_b = 1995;
int choice_c = 3995;
char choice;
int message_units, x=1;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice;
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
do{
cout << "How many message units (enter 1 - 672)" << endl;
// again check this
cin >> message_units;
x++;
}
while(x<2);
if(message_units > 5){
choice_a += 100 * (message_units - 5);
}
cout << "Your total cost is " << choice_a /100 << "." <<choice_a%100 endl
if(message_units > 15){
choice_b += 50 * (message_units - 15);
}
cout <<"Yourtotalcostis"<<choice_b /100 << "." << choice_b%100<<endl;
(You missed an "i" or two, but English is difficult for a non-native speaker.)
Atotalcost = 9.95;
if(messageunits>5)
Atotalcost += 1.0 * (messageunits-5);
EDIT:
There are several ways to deal with amounts of money. One of them is to store an amount as a number of cents, then print it out with care. For example, the amount $2.34 is stored as int price = 234, then to print it out we print price/100 (which is 2), then a decimal point, then price%100 (which is 34, the '%' is the modulo operator, you can look it up). So the code will look like this:
#include <iostream>
using namespace std;
int main()
{
int messageunits;
cout << "how many message units(enter 1 - 672)" << endl;
cin >> messageunits;
int Atotalcost = 995; // cost of package a, in cents
if(messageunits > 5){
Atotalcost += 100 * (messageunits - 5);
}
cout << "Your total cost is " << Atotalcost/100 << "." << Atotalcost%100 << endl;
}
There is still much work to do, but this is a good start.
Along those lines, this example may have a few minor errors and I tried to keep it simple.
#include <iostream>
using namespace std;
int main() {
bool finished = false;
do {
// to keep it simple
double choice_a = 9.95;
double choice_b = 19.95;
double choice_c = 39.95;
char choice;
int message_units;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
// user enters how many units is wanted
cout << "How many message units (enter 1 - 999)" << endl;
// again check this (if homework requires checking input)
cin >> message_units;
// Calculating message units
if (message_units > 5) price += message_units * 1;
else price += message_units * 2; // if $2.00 normal?
// Total Price Output
cout << "Total: " << price << endl;
// Is user done?
char done;
cout << "Do you want to enter another? press enter to continue. If you are done, type something and press enter.";
cin >> done;
// check
if (done != '') {
finished = true;
}
}
while (finished = false);
Alright, that is about it. Two do while loops and the rest. There may be some slight errors while compiling, really, you should try to fix those yourself as this is pretty much the entire assignment...

C++ if/else statements not properly outputting

currently, I am having an issue with this if/else statement. this is the source here:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
string firstname, secondname;
const int A_SCORE = 90;
const int B_SCORE = 80;
const int C_SCORE = 70;
const int D_SCORE = 60;
int testscore1;
int testscore2;
int testscore3;
int testscore4;
int testscore5;
int testscore6;
int testscore7;
int testscore8;
int testscore9;
int testscore10;
cout << "Enter your 10 scores and I will average\n"
<< "the total score, and assign letter grades" << endl;
cin >> testscore1;
cin.ignore();
cin >> testscore2;
cin.ignore();
cin >> testscore3;
cin.ignore();
cin >> testscore4;
cin.ignore();
cin >> testscore5;
cin.ignore();
cin >> testscore6;
cin.ignore();
cin >> testscore7;
cin.ignore();
cin >> testscore8;
cin.ignore();
cin >> testscore9;
cin.ignore();
cin >> testscore10;
cin.ignore();
int sum = testscore1 + testscore2 + testscore3 + testscore4 + testscore5 + testscore6 + testscore7 + testscore8 + testscore9 + testscore10;
int average = sum / 10;
if (average == 90);
{
cout << "your average is an A.";
}
else if (average == 80);
{
cout << "you have an average of a B.";
}
else if (average == 70);
{
cout << "you have an average of a C.";
}
else (average == 60);
{
cout << "your average is a D.":
}
system("pause");
return 0;
}
what the goal of this homework assignment is, is to input 10 numerical grades and have an average print out to screen with a letter grade based on average of the 10 grades. I no matter what I input, I always get 'your grade is an A. I have went over my notes ad well as looking to goodle/StackOverflow for what could be wrong. I also get compile errors too, which I cannot figure out. If someone could give me any ideas on what could be causing the issue, I would greatly appreciate it!
Remove the semicolons after the if statements and instead of checking for the values to be exactly 90/80/70 try something like this:
if(average >= 90)
{
//print
}
If you want more accurate results try using floats instead of integers.
Your if-statements should take the form of if(average >= 90, 80, etc...).
Also, what are your errors?
EDIT:
if (average >= 90)
{
cout << "your average is an A.";
}
else if (average >= 80)
{
cout << "you have an average of a B.";
}
else if (average >= 70)
{
cout << "you have an average of a C.";
}
else if(average >= 60)
{
cout << "your average is a D.";
}
else
{
cout << "your average is an F.";
}
return 0;
You needed to remove all of the semicolons, one colon, change your relational operator from == to >=, and add an extra else to catch anything below 60.
If..else statements are conditional. You need to provide the accurate conditions to get the results that you expect.
Try:
if (average >= A_SCORE)
{
cout << "your average is an A.";
}
else if (average >= B_SCORE)
{
cout << "you have an average of a B.";
}
else if (average >= C_SCORE)
{
cout << "you have an average of a C.";
}
else if(average >= D_SCORE)
{
cout << "your average is a D.";
}
else
{
cout << "your average is an F.";
}
system("pause);

Code not working? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am learning C++. As a homework I've started to try the branching.. but I didn't quite get the hang of it... here's the code I've tried to perform (please bear patience with me if I'm making huge mistakes..)
#include <iostream>
using namespace std;
int main () {
int age;
char * yes;
char * no;
bool Rated = Rated ? yes : no;
int ticketPrice = 5;
int discountPrice = ticketPrice - (ticketPrice * 0.1);
int matineePrice = (ticketPrice * 0.5);
int hour = 8 <= hour <= 24;
cout << "Is the movie R_rated? \n";
cin >> yes or no;
cout << "How old are you?";
cin >> age;
if (age < 0 or age >100) {
cout << "Not a valid age!";
}
else if ((age <= 13) and (Rated = yes)) {
cout << "You must be accompanied by a Janitor";
}
else if (((age > 13) and ((Rated = yes) or (Rated = no)))
or ((age <=13) and (Rated = yes))) {
cout << "What time do you want the ticket for?";
cin >> hour;
if (hour < 8 or hour > 24) {
cout << "Not a valid hour!";
}
else if (hour < 18) {
if (age <= 5) {
cout << "The entrance is free";
}
else if (age >= 55) {
cout << "Matinee Ticket price is "<<
matineePrice;
}
else if (5 < age < 55) {
cout << "Matinee ticket price is " << matineePrice;
}
}
else if (hour >= 18) {
if (age <= 5) {
cout << "The entrance is free";
}
else if (5 < age <= 55) {
cout << "Ticket price is " << ticketPrice;
}
else if (age > 55) {
cout << "You're eligibile for a 10% "
"discount \n";
cout << "Ticket price is " << discountPrice;
}
}
}
}
Output: (to which I answer no, 67, and 20) and I should get the discountedPrice instead of the ticketPrice value...
Is the movie R_rated?
no
How old are you?67
What time do you want the ticket for?20
Ticket price is 5
Any suggestion, link or tutorial help would be really appreciated...
There are a lot of things wrong with your code. I suggest you get a good book on C++ and learn from that. If you're already using a book, chances are that it's not good.
Here are some things, though:
char* is not the right thing to use for strings. You should use the std::string class.
Your entire code surrounding Rated bears little resemblance to C++.
= is the assignment operator. It cannot be used to compare things for equality; that's what == is for.
To start with, get rid of yes and no, which make no sense, and read the input into a string variable:
string Rated;
cin >> Rated;
then to use that, remember to use == not = for comparison:
if (Rated == "yes") {/*whatever*/}
Alternatively, use a boolean variable:
string yes_or_no;
cin >> yes_or_no;
bool Rated = yes_or_no == "yes";
if (Rated) {/*whatever*/}
Also, this:
8 <= hour <= 24
doesn't do what you think it does. You'd need two separate comparisons:
8 <= hour and hour <= 24
although, in this case, you don't want it at all - it doesn't make sense to initialise hour with that. You're reading the value of hour and checking its range later, and don't need to initialise it here.
There are probably more problems, but that should get you started. And I hope I can still go to the cinema when I'm over 100.
The code below is fixed. I've attempted to explain exactly what the code does.
// Declare the input/output streams, including standard streams like std::cin and std::cout.
#include <iostream>
// Declare the std::string class - it's C++, we should not use C strings!
#include <string>
// Instead of using the entire std namespace, we'll only use the things that come up often.
// This saves some typing, but is safe. Otherwise, who knows what name may clash with something
// in the vast std namespace.
using std::cin;
using std::cout;
using std::endl;
int main() {
bool ok; // Whether the most recent answer to a question is valid
bool rated; // Whether the movie is R-rated
int age; // Customer's age
int hour; // Hour of the showing
const int ticketPrice = 5;
const int discountPrice = ticketPrice * (1.0 - 0.9);
const int matineePrice = ticketPrice * 0.5;
// Gather Inputs
do {
std::string answer; // Holds the answer to the yes/no question
cout << "Is the movie R-rated (y/n)? ";
cin >> answer;
if (answer.length() > 0) {
// If the answer is not empty, we can uppercase the first letter.
// This way we don't have to check for lowercase answers.
answer[0] = toupper(answer[0]);
}
// The answer is valid when it's non-empty and when it begins with either Y/y or N/n
ok = answer.length() > 0 and (answer[0] == 'Y' or answer [0] == 'N');
if (not ok) {
cout << "That's not a valid answer." << endl;
} else {
// The answer is valid, so we can set the rated variable.
rated = answer[0] == 'Y';
}
} while (not ok); // Repeat the question while the answer is invalid
do {
cout << "How old are you? ";
cin >> age;
// The answer is valid when it's between 0 and 150, inclusive.
ok = age >= 0 and age <= 150;
if (not ok) {
cout << "That's not a valid age!" << endl;
}
} while (not ok);
do {
cout << "What hour do you want the ticket for? ";
cin >> hour;
// The hour 0 is mapped to 24.
if (hour == 0) hour = 24;
// The answer is valid when it's between 8 and 24, inclusive.
ok = hour >= 8 and hour <= 24;
if (not ok) {
cout << "That's not a valid hour!";
}
} while (not ok);
// Output the Messages
if (rated and age <= 13) {
cout << "You must be accompanied by a Janitor" << endl;
}
if (age <= 5) {
cout << "The entrance is free" << endl;
}
else if (hour < 18) {
cout << "Matinee ticket price is " << matineePrice << endl;
}
else {
if (age <= 55) {
cout << "Ticket price is " << ticketPrice << endl;
}
else {
cout << "You're eligibile for a 10% discount." << endl;
cout << "Ticket price is " << discountPrice << endl;
}
}
}
To start off with:
char * yes;
char * no;
// ...
cin >> yes or no;
makes no coding sense what-so-ever.
In general, "yes" and "no" are not keywords in c++. "true" and "false" are.
Alright, some things:
1)
cin >> yes or no;
should be:
cin >> Rated;
since variable names can't have spaces in them, as you've written it the compiler reads "cin should put something in yes, but I can't figure out what to do with 'or' and 'no'."
2)
else if ((age <= 13) and (Rated = yes))
will never work. I recommend rewriting storing the result in a string (std::string) and then setting rated according to that.
std::string rated_str;
cin >>rated_str;
if(rated_str == "yes") {
rated = true;
} else {
rated = false;
}
and then in the if you use:
if(rated)
or
if(rated == true)
3) You can't reference a variable before it's fully declared:
bool Rated = Rated ? yes : no;
Lines:
bool Rated = Rated ? yes : no;
cin >> yes or no;
and all with
(Rated = yes)
(Rated = no)
have no sense.
First of all, if Rated is bool then you can assign to it only true or false (everything which is not 0 or NULL and what compiler accept would be converted to true).
Best quality code should use enum type for rated.
When you read, you should read to some variable and check its type.
Small fixes for you:
enum EnRated
{
RRated = 0,
NotRRated = 1
};
...
enum EnRated Rated;
string ans; //instead of yes, no
...
cin >> ans;
if(ans == "yes") Rated = RRated;
else Rated = NotRRated; //handle ans != yes or no
...
(Rated == RRated) // instead of (Rated = yes)
(Rated == NotRRated) // instead of (Rated = no)
For discount ticket use:
double discountPrice = 0,9*ticketPrice;
You will input hour and test them, so you can write only:
int hour;
Try this
You are doing a mistake in the following else if statements.
You are not using your else if condition checker properly.
You need not to use or keyword here... actually this is the real problem you are facing here, and you just need to replace your or with and.
For a perfect solution please read the Right approach below
Your code
else if (5 < age <= 55) {
cout << "Ticket price is " << ticketPrice;
}
Right approach
This will give you your discount price
else if (5 < age and age < 55)
{
cout << "Ticket price is " << ticketPrice;
}