Broken While Loop

Hello, I'm trying to figure out why this won't work when I put in a number at the first prompt, and then a 0 at the 2nd or later. It seems to hinge on having double x = 0.0 in there. The thing is, I need to be able to have a user enter values with decimal places.

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
// project2b.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;
#include <iomanip>

int _tmain(int argc, _TCHAR* argv[])
{	
	{
		int x;
		int i=0;
		int sum=0;
		cout << "Please enter a number (0 to quit) --> ";
		cin >> x;
		while (x != 0)
		{
			cout << "Enter the next number (0 to quit) -->";
			cin >> x;
			sum += x; 
			i++;
			double x = 0.0;
		}
		
		cout << setprecision(2) << fixed << "Sum = " << sum << endl;
		cout << setprecision(2) << fixed << "Average = " << sum / i << endl;
	}
   return 0;
}
replace int x; with double x; (line 12)

get rid of double x = 0.0; (line 23)
This should work.

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 "stdafx.h"
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
		float x;
		int i=0;
		float sum;

		cout << "Please enter a number (0 to quit) --> ";
		cin >> x;
		sum = x;

		while (x != 0)
		{
			cout << "Enter the next number (0 to quit) --> ";
			cin >> x;
			sum += x;
			i++;
		}

		cout << fixed << showpoint << setprecision(2) << "Sum = " << sum << endl;
		cout << fixed << showpoint << setprecision(2) << "Average = " << sum / i << endl;

   return 0;
}
Last edited on
Thanks, that fixed it codewalker
Topic archived. No new replies allowed.