I am trying to add to my current program that asks the user to input multiple values. one per line and then output the total sum of all of the values and then also output the number of inputs read or entered. I have been able to have the program ask the user for input values and the summation works and the program outputs the sum of the values. I need help with a switch staement that will keep track and output the number of inputs read. can anyone please help me ?
Below is my code.
#include <iostream>
using namespace std;
int main()
{
float number, sum = 0.0;
do {
cout << "enter number: Enter 0 to end and calculate sum ";
If you want to keep track of how many times the user entered a number, just create a counter, and increase it by 1 each time the user enters something.
#include <iostream>
usingnamespace std;
int main()
{
float number, sum = 0.0;
int counter = 0; // Create counter and initialize to 0.
do
{
cout << "enter number: Enter 0 to end and calculate sum ";
cin >> number;
counter++; // after the user has entered, increase it by 1.
sum += number;
} while (number != 0.0);
cout << "Thank you. The total was: " << sum;
return 0;
}
I would use prefix increment as opposed to postfix increment. Difference between the two is where the ++ goes. And as the names imply, prefix increments a variable, then returns it. Postfix returns the variable then increments it. You get some weird "off by 1" errors depending on how you increment your counters and stuff.
Just be careful with equality operators withfloats or doubles, even though it might work in this situation, there will be values where it doesn't, because FP numbers don't have an exact representation.