Help with do while loops

Write your question here.

int main() {

double num;
double sum = 0;
double avg;
do
{
cout << "Enter a Number (0 to stop): ";
cin >> num;
sum += num;
avg = ((sum += num)/num);
}
while (num != 0);

cout << '\n';
cout << "Sum = "<<sum << endl;
cout << "Average = "<<avg;

return 0;



so this is my code and it runs great! the only problem i am having is having to find the average of the loop. it is not working because it is dividing by infinity so when i compile, the average says inf. also, i need to find how many numbers are positive and negative in a separate cout statement.
Hello swivelchair,


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

It makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.


Also it is best to post the whole code and not something that is missing pieces.

First you are figuring the average inside the do/while loop and it should be done after the loop. You will also need a variable to count how many numbers have been entered because you will need this to figure the average.

This is your code rearranged a bit and changed. Check the comments in the code:
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
29
30
31
32
33
34
35
36
#include <iostream>
#include <limits>

int main()
{

	double num{};
	double count{ -1 };  // <--- Added. Set to -1 so the do/while loop comes out right.
	double sum = 0;
	double avg{};

	do
	{
		std::cout << "Enter a Number (0 to stop): ";
		std::cin >> num;

		sum += num;

		count++;  // <--- Keeps track of how many numbers have been entered.
	} while (num != 0);

	avg = (sum / count);  // <--- Moved and changed.

	std::cout << '\n';
	std::cout << "Sum = " << sum << std::endl;
	std::cout << "Average = " << avg;


	// <--- Keeps console window open when running in debug mode on Visual Studio.
	// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue: ";
	std::cin.get();

	return 0;
}

Hope that helps,

Andy
Thank you! honestly this helps a lot but how would you count the positive or negative numbers that the user entered. Like have a separate cout statement for "Postive numbers entered: " and a cout for "Negative numbers entered: "

Thank you again i have been at this all day long:/
Topic archived. No new replies allowed.