Hey, I've combed through the previous posts and I found something for finding the sum in a loop. Which is essentially what I need to do:
Problem: Create a program that uses a loop to ask the user to enter a series of numbers. The loop will count how many numbers are entered and determine the maximum and minimum values of the numbers enters.
Heres my code:
#include <iostream>
using namespace std;
int main()
{
int numbers_entered = 0;
char letter;
double number;
double max;
double min;
do
{
cout << "Please enter the number." << endl;
cin >> number;
numbers_entered++;
if (numbers_entered==1) { max=number; min=number; } // first number entered
if (number > max) max = number;
if (number < min) min = number;
cout << "Would you like to enter another number? (y/n)? ";
cin >> letter;
} while (letter == 'y' || letter == 'Y');
cout << "You entered " << numbers_entered << " numbers." << endl;
cout << "The maximum number entered is " << max << " and the minimum number entered is " << min << "." << endl;
}
I wanted to manipulate the following code to find a sum:
double sum = 0;
sum+= total;
So with that inserted into my code:
#include <iostream>
using namespace std;
int main()
{
int total, numbers_entered = 0;
char letter;
double number;
double max;
double min;
double sum = 0;
do
{
cout << "Please enter the number." << endl;
cin >> number;
numbers_entered++;
sum+= total;
if (numbers_entered==1) { max=number; min=number; }
if (number > max) max = number;
if (number < min) min = number;
cout << "Would you like to enter another number? (y/n)? ";
cin >> letter;
} while (letter == 'y' || letter == 'Y');
cout << "You entered " << numbers_entered << " numbers." << endl;
cout << "The maximum number entered is " << max << " and the minimum number entered is " << min << "." << endl;
cout << "The sum of the numbers entered is " << total << "." <<endl;
}
However, this generates the sum to be 0. I cant figure it out. Any help would be much appreciated.
Code tags, not quote tags.
I believe it's because you are printing the wrong number. You have outputted total but you are adding to sum. You know how the compound assignment works right?
1 2
sum += total; // is equivalent to
sum = sum + total; // sum is the one increasing, total is unchanged
I changed the code, trying to follow the logic to:
1 2 3 4 5 6
cout << "Please enter the number." << endl;
cin >> number;
total = sum + number;
numbers_entered++;
Im obviously messing up because it continues to print a 0. I am a complete beginner, I am not asking for a "gimmie" but I cant really figure this out. Perhaps another nudge in the right direction if you have some reservations about just providing me with the code.