Need Help Please

Hi,

could anyone help me with this please?

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 ";

cin >> number;

sum += number;

} while (number != 0.0);

cout << "Thank you. The total was: " << sum;

 

 

return 0;

 

 

}

I look forward to your help!
Hey and welcome. For future post, you Should use code tags for all of your code - http://www.cplusplus.com/articles/jEywvCM9/

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.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace 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;

}
How do you increase the counter by 1?
You use the increment operator, as shown by TarikNeaj.

1
2
3
// ++ is the increment operator
// same as doing counter = counter + 1
counter++;
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.

Post goes ++counter
Pre goes counter++
Hi,

Just be careful with equality operators with floats 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.


You could do this instead:

} while ( static_cast<int>(number) != 0 );

Good Luck !!
Topic archived. No new replies allowed.