How to find the average of user inputs - c++

so here is my code (stripped of the headers because that is irrerevelant.)
int main() {
float program = 0;
float scores = 0;
float test = 0;
float testScores = 0;
float e = 1;
float exam = 0;
float programAverage = 0;
cout << "Enter the number of assignments that were graded: ";
cin >> program;
for (int i = 1; i <= program; i++){
cout << "Enter the score for assignment # " << i <<": "; cin >> scores;
}
cout << "Enter the number of test: ";
cin >> test;
for (int e = 1; e <= test; e++){
cout << "Enter the score for test # " << e << ": "; cin >> testScores;
}
cout << "Enter the final exam score: ";
cin >> exam;
programAverage = (scores/program);
cout << "Program Average: " << programAverage << endl;
}
the last part I am having problems because whenever I compile my program the compiler just remembers the last number the user entered and does not average it. How can i get it to add all the user input numbers together and then average?

int main() {
float program = 0;
float scores = 0;
float test = 0;
float testScores = 0;
float e = 1;
float exam = 0;
float programAverage = 0;
float scoresSum = 0; // variable that adds up all the input scores
cout << "Enter the number of assignments that were graded: ";
cin >> program;
for (int i = 1; i <= program; i++){
cout << "Enter the score for assignment # " << i <<": "; cin >> scores;
scoresSum += scores; // adds up all the scores
}
cout << "Enter the number of test: ";
cin >> test;
for (int e = 1; e <= test; e++){
cout << "Enter the score for test # " << e << ": "; cin >> testScores;
}
cout << "Enter the final exam score: ";
cin >> exam;
programAverage = (scoresSum/program); // divide the total score out of program number
cout << "Program Average: " << programAverage << endl;
}
So the problem was that you didn't add up the input scores.
The variable "scores" only has the value of the last input score.
You have to set up a variable to sum up all the input score so far, such as scoresSum in the code.
And add up the score every time a score is submitted.
You can easily find the difference between your code and mine by looking at the line with comment.

float _sum=0;
for (int i = 1; i <= program; i++){
cout << "Enter the score for assignment # " << i <<": "; cin >> scores;
_sum+=i;
}
programAverage = (_sum/program);
cout << "Program Average: " << programAverage << endl;

Well yeah because of this loop, scores always has the last value entered:
for (int i = 1; i <= program; i++){
cout << "Enter the score for assignment # " << i <<": "; cin >> scores;
}
An average is defined as a sum divided by the number of instances. You're not summing, you just keep overwriting "scores" with the last read value when you do cin >> scores. So the problem can be restated as "How can I sum all the numbers the user entered in?" Computers do exactly what you tell them to, and you need to figure out how to exactly tell it to sum all the entered scores.
Well how would you do that in real life? You'd keep a running tally of all the scores, maybe by adding them with a calculator. You'd first initialize a count:
double sum = 0.0;
Then after the line for `cout << "Enter the score..." you add to sum:
sum = sum + scores;
Or C++ has handy shorthand notation
sum += scores

Related

Program doesn't execute for loop until the end

I'm writing a code to enter subjects' information where I put void function and array as an object. But not sure when I wanna loop it, it doesn't come until the end. Have a look at the code.
void calculateCGPA::getGPA() {
cout << "Enter the the name of the subject: ";
cin >> subjectName;
cout << "Enter the credit hour:";
cin >> credithour;
cout << "Enter the grade: ";
cin >> grade;
}
int main () {
for (year=1; year<=4; year++) {
for (sem=1; sem<=2; sem++) {
cout << "Enter total subject you take in Year " << year << " Semester " << sem <<": ";
cin >> totalSubjectSem;
calculateCGPA ob[totalSubjectSem];
for(int i = 1; i <= totalSubjectSem; i++) {
cout << "Subject " << i << ": \n";
ob[i].getGPA();
}
}
}
return 0;
}
Here's the error. You can see the compiler only shows until entering the subject name but credit hour and grade are omitted. What should I do?
Expected: It should everything in void function until 3 (since I put 3) and then start over again "Enter total subject you take in Year 1 sem 2" but it also omits that
Take note that in C++ 0 is the first element, and n-1 is the last element. By looping to n, you cause a buffer overflow, hence resulting an error.
A solution would be as follows
void calculateCGPA::getGPA() {
cout << "Enter the the name of the subject: ";
cin >> subjectName;
cout << "Enter the credit hour:";
cin >> credithour;
cout << "Enter the grade: ";
cin >> grade;
}
int main () {
for (year=0; year<4; year++) {
for (sem=0; sem<2; sem++) {
cout << "Enter total subject you take in Year " << year << " Semester " << sem <<": ";
cin >> totalSubjectSem;
calculateCGPA ob[totalSubjectSem];
for(int i = 0; i < totalSubjectSem; i++) {
cout << "Subject " << i << ": \n";
ob[i].getGPA();
}
}
}
}
calculateCGPA ob[totalSubjectSem];
It's GCC extension called Variable-length automatic arrays and not valid C++ (because totalSubjectSem is not const). Use std::vector<calculateCGPA> instead.
for(int i = 1; i <= totalSubjectSem; i++) {
Indices start from 0 and going to array_length - 1. On last iteration you reading out of array bounds and program is crashing.

Finding sum of User Inputed Values

I need help adding up several user inputed values using C++
double total; // Accumulates total
double price; // Gets next price from user
int numItems; // Number of items
int counter = 1; // Loop control counter
cout << "How many items do you have? ";
cin >> numItems;
cout << endl;
while (counter <= numItems) {
total = 0;
cout << "Enter the price of item " << counter << ": ";
cin >> price;
cout << endl;
total += price;
counter++;
}
cout << "The total price is: " << total << endl;
When I run my code, I end up getting the sum of only one value from the user
Yes, just as Chetan Ranpariya said:
total = 0; should be before while loop.

How do I store the values entered into a for loop by a user?

I have the following code
for (int i = 0; i < courses; i++)
{
cout << "Please Enter Letter Grade: ";
cin >> grade1;
cout << "Please Enter Course Weighting: ";
cin >> weight1;
}
Now, lets say the loop runs 3 times and the values entered by the user for grade1 and weight1 are different each time. I want to store these different values so I can do some calculations with them. How would I proceed to do so?
Here is how use an array:
int grade[courses]; // this is an array with size of courses
double weight[courses];
for (int i = 0; i < courses; i++) {
cout << "Please Enter Letter Grade: ";
cin >> grade[i];
cout << "Please Enter Course Weighting: ";
cin >> weight[i];
}
Array is collection of data of the same type stored sequentially in computer memory. Syntax for array is as follow:
<type> <name>[<size>];
for example
int numberOfStudents[100];
is int array with maximum of 100 elements.
Hope This Helps
group grade and weight into a struct and store them in a vector.
code: (doesnt handle all potential errors)
#include <iostream>
#include <vector>
struct grade_weight
{
int grade;
int weight;
};
int main()
{
int courses = 5;
std::vector<grade_weight> result;
// potential optimization if you want
//result.reserve(courses);
for (int i = 0; i < courses; i++)
{
int grade, weight;
std::cout << "Please Enter Letter Grade: ";
std::cin >> grade;
std::cout << "Please Enter Course Weighting: ";
std::cin >> weight;
result.push_back({grade, weight});
}
std::cout << "you input\n";
for(auto& gw: result)
{
std::cout << "grade: " << gw.grade << ", weight: " << gw.weight << '\n';
}
}

C++: interestEarned coming back wrong

I'm learning C++ and this is an assignment I have to do, it's complete but my interestEarned is not coming back correctly but the bankBalance is correct so I'm just not displaying interestEarned correctly. "Total Interest Earned: $65.50" is incorrect is supposed to display "$120.50" as my teacher said. What am I doing wrong?
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Variables
int numOfCustomers, numOfMonths = 0;
double bankBalance, depositAmount, withdrawnAmount, interestRate, interestEarned = 0.0;
const int MIN = 0;
// Asking for Number of Customers
cout << "Enter the number of customers: ";
cin >> numOfCustomers;
// Making sure the input was not 0 or lower
while (numOfCustomers <= MIN) {
cout << "==>Number of customers must be at least 1. Try again: ";
cin >> numOfCustomers;
}
// Validating each Customer
for (int c = 1; c < (numOfCustomers + 1); c++) {
// Start of each Customer
cout << "\nCUSTOMER " << c << ":\n";
// Asking for Number of Months --
cout << "Enter the number of months the account has been opened: ";
cin >> numOfMonths;
// Making sure the input was not 0 or lower
while (numOfMonths <= MIN) {
cout << "==>Number of months must be at least 1. Try again: ";
cin >> numOfMonths;
}
// Asking for Starting Balance --
cout << "Enter the starting balance: $";
cin >> bankBalance;
// Making sure the input was not 0 or lower
while (bankBalance < MIN) {
cout << "==>Starting balance can't be negative. Try again: $";
cin >> bankBalance;
}
// Asking for Monthly Interest Rate --
cout << "Enter the monthly interest rate as a decimal (i.e. 0.05 = 5%): ";
cin >> interestRate;
// Making sure the input was not 0 or lower
while (interestRate < MIN) {
cout << "==>Monthly interest rate can't be a nagative. Try again: ";
cin >> interestRate;
}
// Validating each Month
for (int m = 1; m < (numOfMonths + 1); m++) {
// Deposit Amount
cout << "\nEnter deposit amount for Month " << m << ": $";
cin >> depositAmount;
bankBalance = bankBalance + depositAmount;
// Withdrawn Amount
cout << "Enter withdrawn amount for Month " << m << ": $";
cin >> withdrawnAmount;
bankBalance = bankBalance - withdrawnAmount;
// Calculating Interest Earned
interestEarned = bankBalance * interestRate;
// Complete bankBalance
bankBalance = bankBalance + interestEarned;
}
// Account Summary
cout << "\nACCOUNT SUMMARY" << endl;
cout << fixed << setprecision(2);
cout << "Number Months Active: " << numOfMonths << endl;
cout << "Ending Balance: $" << bankBalance << endl;
cout << "Total Interest Earned: $" << interestEarned << endl;
}
system("pause");
return 0;
}
Use another variable that is initialized to zero before the loop. In the loop, add the value of interestEarned to it. - #Peter

Simple grading program returning the wrong answer

Trying to write a simple program that takes six test grades, input by the user, drops the lowest, and then displays average of the remaining five. The program compiles fine, but outputs the wrong answer. Any pointers to where the logic error is occurring would be helpful. I am using these values as sample grades:
85.2
92.3
78.0
51.5
91.6
87.0
and the value returned should be 86.82, but the program is instead returning 80.08.
#include <iostream>
using namespace std;
const int SIZE = 6;
double grades[SIZE];
double low(double[]);
int main()
{
double preavg = 0;
double avg = 0;
cout << "This program will take an input of six test grades\n"
<< "and determine the average of the highest five grades.\n\n"
<< "Please input the first test grade\n";
cin >> grades[0];
cout << "Please input the second test grade\n";
cin >> grades[1];
cout << "Please input the third test grade\n";
cin >> grades[2];
cout << "Please input the fourth test grade\n";
cin >> grades[3];
cout << "Please input the fifth test grade\n";
cin >> grades[4];
cout << "Please input the sixth test grade\n";
cin >> grades[5];
for (int i = 0; i < SIZE; i++)
{
preavg += grades[i];
}
avg = (preavg - low(grades)) / (SIZE -1);
cout << "Your average grade is " << avg << "\n";
system("PAUSE");
return 0;
}
double low(double grades[SIZE])
{
double lowest;
lowest = 100;
for (int i = 0; i < SIZE; i++)
{
if (grades[i] < lowest)
lowest = grades[i];
}
return lowest;
}
Your issue here is possibly coming from the fact you're doing division in double precision using a const int. If you cast SIZE as a double and write the rest of your double numbers with a .0 on the end, it works fine:
#include <iostream>
using namespace std;
const int SIZE = 6;
double grades[SIZE];
double low(double[]);
int main()
{
double preavg = 0.0;
double avg = 0.0;
cout << "This program will take an input of six test grades\n"
<< "and determine the average of the highest five grades.\n\n"
<< "Please input the first test grade\n";
cin >> grades[0];
cout << "Please input the second test grade\n";
cin >> grades[1];
cout << "Please input the third test grade\n";
cin >> grades[2];
cout << "Please input the fourth test grade\n";
cin >> grades[3];
cout << "Please input the fifth test grade\n";
cin >> grades[4];
cout << "Please input the sixth test grade\n";
cin >> grades[5];
for (int i = 0; i < SIZE; i++)
{
preavg += grades[i];
}
avg = (preavg - low(grades)) / ((double)SIZE - 1.0);
cout << "Your average grade is " << avg << "\n";
system("PAUSE");
return 0;
}
double low(double grades[SIZE])
{
double lowest;
lowest = 100.0;
for (int i = 0; i < SIZE; i++)
{
if (grades[i] < lowest)
lowest = grades[i];
}
return lowest;
}