C++ if/else statements not properly outputting - c++

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);

Related

Ask for the condition of guess number game

I am a newbie, i have some question:
I am coding a guessing number game, player enter the random number range, guess number, guess limit. When player enter the guess number out of the random range entered, the program require player to enter the guess number again. However, I tested my code, I entered the number range [ 3,8 ] and the guess number is 1, this number is out of range, the program didn't force me to enter the guess number again but I had to enter the guess limit. Please hint me what's wrong with my code and help me to fix this code. Thanks!
#include iostream
#include cstdlib
using namespace std;
int randnum(int min, int max)
{
return min + (int)(rand() * (max - min + 1.0) / (1.0 + RAND_MAX));
}
int main()
{
int max;
int min;
int guessnum;
int guesscou = 0;
int guesslim;
bool outofguess = false;
cout << " Enter max min of random value range = \n ";
cin >> max >> min;
cout << " Enter your guess number = \n ";
cin >> guessnum;
cout << " Enter your guess limitation = \n";
cin >> guesslim;
// enter guess loop
while (guessnum != randnum(min, max) && !outofguess) {
// guessnum condition
while (guessnum <= max && guessnum >= min) {
cout << " Unvalid number, please enter again ";
cin >> guessnum;
}
// guess limitation
if (guesscou <= guesslim) {
cout << " Please try again \n";
cin >> guessnum;
guesscou++;
}
else {
outofguess = true;
}
}
if (outofguess) {
cout << " you win";
}
else {
cout << " you lose ";
}
}
You want the user to guess again if the number is lower than the minimum or higher than the maximum. But the logic in your while loop says exactly the opposite. It should read
while (guessnum < min || guessnum > max) {
cout << " Unvalid number, please enter again ";
cin >> guessnum;
}

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.

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")

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

Can't get function to work right. Extra numbers that shouldn't be displayed

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().