Trouble with output

Hey all,
I'm writing a program that finds the root mean square of a series of numbers the user inputs. When the user wants to exit the program they will enter -1 and the final answer will be displayed. If the user enters no data (they enter -1 on the first input) then it should display "no data". The trouble I am having is that whenever the user enters -1 both the "Answer" and "no data" are displayed. Does anyone know what I am doing wrong??

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
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	double number = 0, squared = 0, total = 0, divide = 0, root = 0;
	int counter = 0;
	while (number != -1)
	{
		cout << "Enter a positive number (-1 to exit): ";
		cin >> number;
		counter++;

		if (number >= 0)
		{
			squared = pow(number, 2);
			total += squared;
			divide = (total / counter);
			root = sqrt(divide);
		}
	}
			cout << "Answer = " << root << endl;

			if (number == -1)
			{
				cout << "No data" << endl;
			}		


}
Your program prints "Answer = " before it checks to see if -1 was entered.
Thanks for the reply. Even if I switch the statements around it still displays both "answer =" and "no data".
I'm sorry...I should be more clear. You're putting cout << "Answer = " << root << endl; outside of the if(number >= 0)while(number != -1) loop. You shouldn't do that, because the way you wrote it, no matter what order you put it in, it will always print.
Last edited on
When I put the cout << "Answer="... statement inside the while loop it prints the "answer =" after each input. I only want it to print when the user exits the program (enters -1).
Then do this:
1
2
3
4
5
6
7
8
if(root == 0)
{
    cout << "No data" << endl;
}
else
{
    cout << "Answer == " << root << endl;
}
Topic archived. No new replies allowed.