- #1
MostlyHarmless
- 345
- 15
Homework Statement
I'm to write a program that calculates GPA using loops to allow numerous inputs and using Error checking to be sure that inputs are valid.
I'm having trouble figuring out how to make my loop repeat if a the input is invalid.
And I'm also having a little trouble with the stop condition, currently I have the loop break if the user inputs -1 for both of the requested inputs, but what I wanted is for the loop to break if the Grade input is -1 and then not continue to the Credit hour input.
*I forgot to add, I'm not allowed to use arrays in this assignment.*
Homework Equations
The Attempt at a Solution
Code:
#include <iostream>
using namespace std;
int main ()
{
//Defining variables that will be used during code.
float CreditHours;
int LetterGrade;
float Total;
float TotalCredits = 0;
float TotalPoints = 0;
//Asking for input from user
cout <<"Please enter the grade for your class: 4 for A, 3 for B, 2 for C, 1 for D, 0 for F, or '-1' when you're $
cin >> LetterGrade;
// Logic to ensure valid letter grade input
// if (LetterGrade =
cout << "Please enter the credit hours for the previously entered grade: \n";
cin >> CreditHours;
//initializing the loop for more grade inputs
//FIX LOOP
while (LetterGrade != -1)
{
//Updating Totals
Total = LetterGrade * CreditHours;
TotalPoints = TotalPoints + Total;
TotalCredits = TotalCredits + CreditHours;
cout << "Please enter the grade for your class: 4 for A, 3 for B, 2 for C, 1 for D, 0 for F, or -1 when you're d$
cin >> LetterGrade;
cout << "Please enter the credit hours for the previously entered grade: \n";
cin >> CreditHours;
//Incomplete/Questionable
//if (CreditHours <= 0)
// cout << "Please be sure your Credit Hours add up to a positive, non-zero value\n";
}
if (TotalCredits > 0)
{
//Calculating and printing the final GPA.
float gpa = TotalPoints / TotalCredits;
cout << "Your GPA is:"<< gpa <<endl;
}
return 0;
}
Code:
Please enter the grade for your class: 4 for A, 3 for B, 2 for C, 1 for D, 0 for F, or '-1' when you're done inputting grades:
4
Please enter the credit hours for the previously entered grade:
3
Please enter the grade for your class: 4 for A, 3 for B, 2 for C, 1 for D, 0 for F, or -1 when you're done inputting grades:
4
Please enter the credit hours for the previously entered grade:
3
Please enter the grade for your class: 4 for A, 3 for B, 2 for C, 1 for D, 0 for F, or -1 when you're done inputting grades:
-1
Please enter the credit hours for the previously entered grade:
-1
Your GPA is:4
Last edited: