I have a program that asks a user how many quizzes they would like to input, stores the grades, and the computes the average. The grade has to be between 0 and 100. However, when I enter a grade above 100 the average is wrong. It does not reset the sum. If I enter 120 and it prompts me to reenter the grades, it still uses 120 when calculating the average. How do I get it to reset?
Note: I do not want to change the the format (such as using a while loop).
#include <iostream>
using namespace std;
int main(){
int n, i;
float num[13], sum=0.0, average;
cout << "Enter the numbers of quizzes from 1-13: ";
cin >> n;
while (n < 1 || n > 13)
{
cout << "You must enter a number from 1 - 13." << endl;
cout << "Enter the number of quizzes you would like to input(1-13): “;
cin >> n;
}
for(i=0; i<n; ++i)
{
cout << i+1 << ". Enter number: ";
cin >> num[i];
sum+=num[i];
while (num[i] < 0 || num[i] > 100)
{
cout << “You must enter a number between 0 and 100. Re enter scores.”;
cout << i+1 << ". Enter number: ";
cin >> num[i];
}
}
average=sum/n;
cout << "Average = " << average;
return 0;
}
Just put the sum+=num[i] behind the while (num[i] < 0 || num[i] > 100) ... loop !
This way you only sum up valid numbers.
for(i=0; i<n; ++i)
{
cout << i+1 << ". Enter number: ";
cin >> num[i];
//sum+=num[i]; remove here !!
while (num[i] < 0 || num[i] > 100)
{
cout << “You must enter a number between 0 and 100. Re enter scores.”;
cout << i+1 << ". Enter number: ";
cin >> num[i];
}
sum+=num[i]; // <- insert here
}
for(i=0; i<n; ++i)
{
cout << i+1 << ". Enter number: ";
cin >> num[i];
while (num[i] < 0 || num[i] > 100)
{
cout << “You must enter a number between 0 and 100. Re enter scores.”;
cout << i+1 << ". Enter number: ";
cin >> num[i];
}
}
sum+=num[i];
average=sum/n;
cout << "Average = " << average;
return 0;
}
Related
how to show output ( Number of grades above the Average + Grades above or equal the Average ) in same line i don't wont new line for each number + how to print these one time not many times , i mean because i use for loop it print Number of grades above the Average every number in one line i want just the count in one line how to do this
#include <iostream>
using namespace std;
int main()
{
int G,N;
float num[100], sum=0.0, average;
cout << "Enter the numbers of Student : ";
cin >> N;
while (N > 500 || N <= 1)
{
cout << "Error ! number of student should in range of (1 to 500)." << endl;
cout << "Enter the number again: ";
cin >> N;
}
for(G = 0; G < N; ++G)
{
cout << G + 1 << ". Enter " << G + 1 << " Mark : ";
cin >> num[G];
sum += num[G];
}
// find average
average = sum / N;
cout <<endl<< "Grades Average = " << average <<endl<<endl;
// find Grades above or equal the Average
cout<<"Grades above or equal the Average : "<< endl;
for (G = 0; G < N; ++G){
if (num[G] >= average){
cout << num[G] << endl;
}
}
// find Number of grades above the Average
cout<<endl;
for (G = 0; G < N; ++G){
if (num[G] >= average){
cout << "Number of grades above the Average : " << G + 1 << endl;
}
}
return 0;
}
There are a number of issues with your code:
num[] can hold 100 values max, but you are allowing the user to enter up to 500 values into it, thus you have the potential for a buffer overflow.
you say the valid number of students is 1 to 500, but you are preventing the user from entering 1.
lack of adequate error handling when reading the user's input.
you are outputting "Number of grades above the Average : " inside the loop for every matching grade, which you say you don't want. You should instead output it once before entering the loop, then use the loop to count the matching grades without outputting each one, then output the final count after the loop is finished.
Try this:
#include <iostream>
#include <limits>
using namespace std;
const int maxStudents = 500;
int main()
{
int G, N, nAverages = 0;
float num[maxStudents], sum = 0.0, average;
cout << "Enter the number of Students : ";
do
{
if (cin >> N)
{
if (N >= 1 && N <= maxStudents)
break;
cout << "Error ! Number of students should be in range of (1 to " << maxStudents << ")." << endl;
}
else
{
cout << "Error ! Invalid input." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Enter the number again: ";
}
while (true);
for(G = 0; G < N; ++G)
{
cout << G + 1 << ". Enter Mark : ";
while (!(cin >> num[G]))
{
cout << "Error ! Invalid input." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter the mark again: ";
}
sum += num[G];
}
// find average
average = sum / N;
cout << endl << "Grades Average = " << average << endl << endl;
// find Grades above or equal the Average
cout << "Grades above or equal the Average : " << endl;
for (G = 0; G < N; ++G){
if (num[G] >= average){
cout << G + 1 << ": " << num[G] << endl;
++nAverages;
}
}
// Number of grades above the Average
cout << endl << "Number of grades above the Average : " << nAverages << endl;
return 0;
}
I am fairly new to C++, I am trying to write a code that allows input number of reviewers then allows number of reviewers to enter movie rating and display asterisks based on the number input. I am having difficulty incorporating an if statement that display "Movie ratings must be from 1 to 5." when the user input any number that's outside of 1 to 5. Another thing when it does work, it still continues the for loop of cout << "\nReviwer " << r << " rating: " ; instead of stopping and restarting. Any assistance is appreciated.
complied code
int reviewers;
int rating;
//input how many reviewers will be reviewing
cout << "How many reviewers? ";
cin >> reviewers;
cout << "Movie ratings must be from 1 to 5." << endl;
for (int r = 1; r <= reviewers; r++) {
cout << "\nReviwer " << r << " rating: ";
cin >> rating;
if (rating < 1 || rating > 5)
cout << "Movie ratings must be from 1 to 5." << endl;
else {
for (int j = 1; j <= rating; j++) {
cout << "* ";
} //end for
cout << endl;
} //end if
} //end for
Output example should be like this
You should have
#include <iostream>
#include <string>
using namespace std;
int main(){
int reviewers;
int rating;
//input how many reviewers will be reviewing
cout << "How many reviewers? ";
cin >> reviewers;
cout << "Movie ratings must be from 1 to 5." << endl;
for (int r = 1; r <= reviewers; r++) {
cout << "\nReviwer " << r << " rating: ";
cin >> rating;
while (rating < 1 || rating > 5){
cout << "Movie ratings must be from 1 to 5." << endl;
cout << "\nReviwer " << r << " rating: ";
cin >> rating;
}
if (rating >= 1 && rating <=5){
for (int j = 1; j <= rating; j++) {
cout << "* ";
} //end for
cout << endl;
} //end if
} //end for
}
};
It's not optimised but do the trick
if your mean is the reviewer must input the number between 1 and 5,
you can use a do while loop like this:
do
{
//enter rating;
}while (rating < 1||rating >5);
//print out rating;
I suppose you aim at something like this:
int reviewers;
int rating;
//input how many reviewers will be reviewing
cout << "How many reviewers? ";
cin >> reviewers;
cout << "Movie ratings must be from 1 to 5." << endl;
for (int r = 1; r <= reviewers; r++) {
while(true) {
cout << "\nReviewer " << r << " rating: ";
cin >> rating;
if (rating < 1 || rating > 5) {
cout << "Movie ratings must be from 1 to 5." << endl;
} else {
break;
}
}
for (int j = 1; j <= rating; j++) {
cout << "* ";
} //end for
cout << endl;
} //end for
Here is some code I quickly put together. I hope the comments are useful and if you have any questions just ask!
The main part is the recursive function get_ratings which will loop forever until it returns 1
// All this function does is returns the correct amount of stars
// E.G. make_stars(4) returns " * * * *"
string make_stars(int star_Count) {
string stars;
for (int i = 0 ; i < star_Count ; i++) {
stars += " *";
}
return stars;
}
// We get the ratings and returns 1 or 0 depending of it succeeded or failed
int get_ratings(int reviewer_count) {
// We initialise the ratings integer
int rating;
// We loop through all reviewers
for (int i = 0 ; i < reviewer_count ; i++) {
// We do i + 1 so it is more readable (usually in English we start at 1 not 0 like computers)
cout << "What is reviewer " << (i + 1) << "'s rating?" << endl;
//We get the user input
cin >> rating;
// We check to see if rating is withing the range. We could also do is NOT in the range and flip line 27 and 29
if (1 <= rating && rating <= 5) {
// If it is within range we will print the correct amount of stars
cout << make_stars(rating) << endl;
} else {
// We return 0 so we can determine the function "failed"
return 0;
}
}
// We return 1 so we can determine the function "succeeded"
return 1;
}
// This is a recursive function (it can run itself)
int get_ratings_rec(int reviewers) {
cout << "All ratings must be given between 1 and 5 (inclusive)" << endl;
// get_ratings_status is equal to 1/0 depending on if get_ratings() succeeded or failed
int get_ratings_status = get_ratings(reviewers);
if (get_ratings_status == 1) {
// If it was a success we print "Success!"
cout << "Success!" << endl;
} else {
// If it was a failure we tell the user and run get_ratings_loop() again until it succeeds
cout << "Failed, please try again\n" << endl;
get_ratings_loop(reviewers);
}
}
// Our main entry point to the program
int main() {
// We initialise the reviewers integer
int reviewers;
cout << "How many reviewers?\n>>> " << endl;
cin >> reviewers;
// We run get_ratings_loop() with the integer given
get_ratings_loop(reviewers);
}
You'd want to keep asking the number of stars if the user inputs a value outside the range, something like:
for (int r = 1; r <= reviewers; r++)
{
cout << "\nReviwer " << r << " rating: ";
do
{
cin >> rating;
if (rating < 1 || rating > 5) // print error message
cout << "Movie ratings must be from 1 to 5." << endl;
} while (rating < 1 || rating > 5); // repeat the loop if out of range
for (int j = 1; j <= rating; j++)
{
cout << "* ";
} //end for
cout << endl;
}
Note that you should be doing input validation also, e.g., if the input is an alphabetic character, your code will trigger an infinite loop, here an example of a possible solution:
#include <limits>
//...
do
{
if (!(cin >> rating))
{
std::cout << "Bad input, try again";
cin.clear(); //clear error flags
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // clear buffer
rating = 0;
}
if (rating < 1 || rating > 5)
cout << "Movie ratings must be from 1 to 5." << endl;
} while (rating < 1 || rating > 5);
it's required to design a system that takes all the data relevant to the student such as, name,ID,no.of subjects ,and their marks. it's required that when i search for a specific student to show all the data about him and to calculate his gpa and print the result. i tried but the output wasn't as expected and here's my code:
//how the data is read in the txt file`
void enter()
{
ofstream file1("cairo.txt", ios::app);
cout << "Enter the student's name : ";
getline(cin, name);
file1 << name << "\t";
cout << "Enter the student's ID : ";
cin >> std_num;
file1 << std_num << "\t";
cout << "Enter your department : ";
cin.ignore();
getline(cin, department);
file1 << department << "\t";
cout << "Enter the student's number for subjects : ";
cin >> num_sub;
file1 << num_sub << "\t";
for (int i = 0; i < num_sub; i++) {
cout << "please enter the student's " << i + 1 << " " << "mark \n";
cin >> grades[i];
file1 << grades[i] << "\t";
}
file1 << "\n";
file1.close();}
void get_grades()
{
char name[30], id[10], dep[25], city[15], resd[15], zip[15];
int nsub,nmarks[10];
float sum = 0;
ifstream gfile("students.txt");
char rq[30];
cout << "Enter the name of the required student to get his grades : ";
cin.getline(rq, 25);
while (!gfile.eof())
{
if (strcmp(name, rq) == 0)
{
gfile.getline(name, 30, '|');
gfile.getline(id, 10, '|');
gfile.getline(dep, 25, '|');
gfile >> num_sub;
for (int i=0; i < nsub; i++)
{
gfile1>>nmarks[i];
sum += nmarks[i];
}
psum = (sum/(nsub*100));
if (psum < 0.5)) cout<<" Your Grade is F "<<endl;
else if (psum >= 0.5 && psum < 0.65) cout<<" Your Grade is D "<<endl;
else if (psum >= 0.65 && psum < 0.75) cout<<" Your Grade is C "<<endl;
else if (psum >= 0.75 && psum < 0.85) cout<<" Your Grade is B "<<endl;
else cout<<" Your Grade is A "<<endl;
}
}
}
Okay so I when I run this code I get that my total is equal to 0 and that
messes up my average and grade.I am not sure what I am doing wrong as the
total += scores function is where it should be, yet it is still not adding up
the scores.
int validateNumber(int, int, int);
in main() function
int num, score, total = 0;
and
validateNumber(num, score, total);
and the definition
int validateNumber(int num, int score, int total) {
while (num < 1 || num > 4) {
cout << over3 << num << " is not between 1 and 4! Try again: ";
cin >> num;
}
system("CLS");
for (int i = 1; i <= num; i++) {
cout << over3 << "Enter score " << i << ": " << endl;
cout << over3 << "Enter a value from 0 to 100: ";
cin >> score;
while (score < 0 || score > 100) {
cout << over3 << score
<< " is not between 0 and 100! Renter the score: " << i << ": ";
cin >> score;
}
total += score;
}
return total;
}
If you want to implement the validate() function like you did here,
validateNumber(num,score,total);
you can make it void and pass the variable total as reference. e.g,
void validateNumber(int num, int score, int &total) {
while (num < 1 || num > 4) {
cout << over3 << num << " is not between 1 and 4! Try again: ";
cin >> num;
}
system("CLS");
for (int i = 1; i <= num; i++) {
cout << over3 << "Enter score " << i << ": " << endl;
cout << over3 << "Enter a value from 0 to 100: ";
cin >> score;
while (score < 0 || score > 100) {
cout << over3 << score
<< " is not between 0 and 100! Renter the score: " << i << ": ";
cin >> score;
}
total += score;
}
}
and the rest would be same...
Otherwise I wouldn't have use 3 arguments in this case. e.g,
int validateNumber(int num) {
int total=0,score;
while (num < 1 || num > 4) {
cout << over3 << num << " is not between 1 and 4! Try again: ";
cin >> num;
}
system("CLS");
for (int i = 1; i <= num; i++) {
cout << over3 << "Enter score " << i << ": " << endl;
cout << over3 << "Enter a value from 0 to 100: ";
cin >> score;
while (score < 0 || score > 100) {
cout << over3 << score
<< " is not between 0 and 100! Renter the score: " << i << ": ";
cin >> score;
}
total += score;
}
return total;
}
and the call:
int num, total;
...
total=validateNumber(num);
Hope it helped...
Are you assuming the function call validateNumber(num,score,total); in line 5 would calculate the total? You should call the function from main function, and assign the return value to a variable, (e.g. total).
*edit: Fixed the code after realizing I was being a dumbass
Fixed code that works:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int one, two, three = 0, highnum, lownum;
cout << "Enter your first integer: ";
cin >> one;
cout << "\nEnter your second integer: ";
cin >> two;
if (one > two)
{
highnum = one;
lownum = two;
}
while (one != -99 && two != -99 && three != -99)
{
cout << "\nEnter integers until you want to stop (-99 to stop): ";
cin >> three;
if (three > one && three > two || three < one && three < two )
{
if (three > one && three > two && three > lownum)
{
highnum = three;
}
else if ( three < one && three < two && three < lownum)
{
lownum = three;
}
}
else if (one > three && one > two || one < three && one < two)
{
if (one > three && one > two)
{
highnum = one;
}
else if (one < three && one < two)
{
lownum = one;
}
}
else if ( two > three && two > one || two < one && two < three)
{
if ( two > three && two > one)
{
highnum = two;
}
else if (two < one && two < three)
{
lownum = two;
}
}
}
cout << "Your lowest number is: "<< lownum << endl << "Your highest number is: " << highnum << endl << endl;
return 0;
}
I am not sure if arrays are the way to go for this type of problem, as we have yet to learn them in our lecture, but I am having some trouble finding the logic behind this looping structure and how to store an infinite number of variables until -99 is entered. Any help is appreciated
The assignment text:
Write a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.
So far I have taken two different approaches using different combinations of while and for loops, but so far, no dice. Anyone have any suggestions?
Here are the two different versions of the code
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
/*
int one, two, three=0;
cout << "Enter your first integer: ";
cin >> one;
cout << "Enter you second integer: ";
cin >> two;
while ( one != -99 && two != -99 && three != -99 )
{
cout << "Enter another integer. To stop the program enter -99: ";
cin >> three;
}
if (one < two && three)
cout << one << endl;
else if (two < one && three)
cout << two << endl;
else if (three < one && two)
cout << three << endl;
return 0;
*/
And here is my second attempt:
int number, number2, number3, counter = 1;
double mul = 1;
cout << "Enter your first number that is not -99";
cin >> number;
while (number !=-99)
{
cout << "Please enter your second number " <<endl<<endl;
cin >> number2;
}
for (number != -99; number != -99; counter ++)
{
cout <<"Please enter another number. ";
cin >> number3;
}
if (number < number2 && number3)
{
cout << "The low number is " << number << endl;
if (number2 < number3)
cout << "The high number is " << number3 << endl;
}
else if (number2 < number && number3)
{
cout<< "The low number is " << number2 << endl;
if (number < number3)
cout << "The high number is " << number3 << endl;
}
else if (number3 < number && number2)
{
cout << "The low numer is " << number3 << endl;
if (number < number2)
cout << "The high number is " << number2 << endl;
}
Your code and your question title is a little bit controversy.
Based on what I understand about your question, you enter a series of numbers, and when -99 is entered the program will output min, max; but your code is keep entering 2 numbers, compare them and produce output until -99 is entered.
Here is just my raw code, it's not tested yet.
int main() {
int max, min, number;
cout << "Enter your number (not -99): ";
cin >> number;
max = number;
min = number;
while(1) {
cout << "Enter your number (-99 to stop): ";
cin >> number;
if (number == -99) { break; }
if (max < number) { max = number; }
if (min > number) {min = number; }
}
cout << "max: " << max << endl;
cout << "min: " << min << endl;
return 0;
}
The following code should work granted a user doesn't enter numbers greater than or less than 1000000.
int max,min,input;
max = -1000000;
min = 1000000;
cout << "Enter number: ";
cin >> input;
while(input!=-99){
if(input<min) min = input;
if(input>max) max = input;
cout << "Enter number: ";
cin >> input;
}
cout << "Max: " << max << endl;
cout << "Min: " << min << endl;
/I encountered this question tonight and came up with this solution/
#include <iostream>
using namespace std;
int main()
{
int inputNum, lownum, highnum;
cout << "Enter as many numbers as you'd like and then I'll show you which\n";
cout << "was highest and which was lowest.\n";
cout << "Enter -99 to end program.\n\n=>";
cin >> inputNum;
//If user enters -99 right away
if (inputNum == -99)
{
cout << "Ok, we'll thanks for playing anyway\n";
cin.ignore(); //This & next line pause program after ending.
cin.get();
return 0;
}
//assign first input number to both high & low values
highnum = inputNum;
lownum = inputNum;
while (inputNum != -99)
{
cout << "Input number\n=>";
cin >> inputNum;
if (inputNum == -99)
{
break;
}
if (inputNum > highnum)
highnum = inputNum;
if (inputNum < lownum)
lownum = inputNum;
}
cout << "Low number was " << lownum << endl;
cout << "High number was " << highnum << endl;
cin.ignore(); //This & next line pause program after ending.
cin.get();
return 0;
}