Task: Write a program that would (theoretically) remain open, and allow users to enter numbers throughout the day. Users can enter numbers between 0 and 50. Numbers outside of that range, except -999, are invalid and the user must re-enter a valid number. When a user enters the number, it is added to the sum, and the number of users using the program is incremented. When the value -999. When -999 is entered, the total number of students, total textbooks, and the average number of textbooks are printed.
#include <iostream>
using namespace std;
int main () {
const int minBooks = 0, maxBooks = 50;
int books;
int sum=0;
int student = 1;
do {
cout << "Books: " << endl;
cin >> books;
student ;
sum = books;
if (books == -999) {
cout << "Books: " << sum << "\n" << "Students: " << student << "\n" << "Average" << sum/student<< endl;
break;
}
while (books < minBooks || books > maxBooks)
{
cout << "You should at least have " << minBooks << " but no more than " << maxBooks << endl;
cout << "How many books did you purchased?"<< endl;
cin >> books;
}
} while (books!= -999);
}
My problem is that I cant make a program exit after user input is -999. I tried to change place, use in the loop, out of the loop If -999 works, then it doesn't validate the input
changed while for "if" and now it works however, it doesn't sum up books and takes only last input which is -999
after changing books for sum in two place, now my average is not correct due wrong amount of student; I tried to do decremation but then my average becomes negative
CodePudding user response:
FIGURED IT OUT, THANKS EVERYONE FOR HELP! Here are some changes that helped:
#include <iostream>
using namespace std;
int main () {
const int minBooks = 0, maxBooks = 50;
int books;
int sum=0;
int student = 0;
do {
cout << "Books: " << endl;
cin >> books;
student ;
sum = books;
if (books == -999) {
student = student - 1;
sum = 999;
cout << "Here is your summary: " << endl;
cout << "Books: " << sum << "\n" << "Students: " << student << "\n" <<
"Average: " << sum/student<< endl;
break;
}
while (books < minBooks || books > maxBooks)
{
cout << "You should at least have " << minBooks << " but no more than " << maxBooks << endl;
cout << "How many books did you purchased?"<< endl;
cin >> books;
}
} while (books!= -999);
}