#include <iostream>
using namespace std;
int main()
{
int total, // added total of grades
grade, // grade entered for average
x, // variable = to number of grades entered
average; // total of the grades divided by x (defined below)
total = 0; // default total
x = 0; // default # of grades
do
{
cout << "Enter grade, -1 to end: ";
cin >> grade;
total = total + grade;
x = x + 1;
}
while ( grade != -1 ); // continue to loop while -1 is not set as input
cin.ignore(); // ignore input
x = x - 1; // added code to counteract -1
total = total + 1; // added code to counteract -1
if ( total > -1 ) // proceed only if total is greater than -1
{
average = total / x;
cout << "You average is " << average << "." << endl;
}
else // proceed to this only if "if" statement = FALSE
{
cout << "No grades were entered." << endl;
}
cin.get(); // receive input at end to keep window active after executing complete
return 0;
}
// All grades will return integers, no decimals will be displayed, nor can you enter decimals
code for averaging grades
here's a source code someone can use for reference to the do..while function and the if/else statement.
tho the code does work perfectly fine, i would like the code to be a bit shorter. where it's labeled "added code to counteract -1" i should not have to put those, but i can't get it to work that way again. i know i can delete them by setting total to 1 and x to -1, but i shouldn't have to do that either. if someone can find a way around this, that would be great. if not, oh well, at least the code works correctly.
#include <iostream>using namespace std;int main(){ int total, // added total of grades grade, // grade entered for average x, // variable = to number of grades entered average; // total of the grades divided by x (defined below) // Initialize the local variables total = x = 0; do { cout << "Enter grade, -1 to end: "; cin >> grade; // if the user input was -1, do not take it into calculation. if( grade == -1 ) break; total += grade; x++; } while ( grade != -1 ); // continue to loop while -1 is not set as input cin.ignore(1000, '\n'); // ignore input if ( x > 0 ) // proceed only if user has entered at least 1 input { average = total / x; cout << "Your average is " << average << "." << endl; } else // proceed to this only if "if" statement = FALSE { cout << "No grades were entered." << endl; } cin.get(); // receive input at end to keep window active after executing complete return 0;}// All grades will return integers, no decimals will be displayed, nor can you enter decimals
Your source code does not work correctly. What if the user enters 5 zeros? The total is still zero, and your code will see this as no user input.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement