Program Flaws with Loops

This program should terminate if a negative number is entered.
If a character is entered, program should ask for reinput.

This isn't exactly functioning as desired. What am I doing wrong?
(For reference, an input of 5 should output 2.5)

Thank you.

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

int main(){
   
	double n, var, sum=0, average;
	cout << "Enter positive integer N: ";		
	cin >> n; var = n;
    
    for (int x = 0; x <= var; x++)
		{
			sum = sum + n;
			var = (var - 1.0);
			average = sum / (n + 1.0);
					
					while (cin.fail())
					{
						cin.clear();
						cin.ignore();
						cout << "Bad input. Try again.";
						cin >> n;
					}
		}

	if (n < 0)	// Terminates Program if Input is Negative
		{ 
			return 0;
		}

	cout << "The mean of all integers from 0 to " << n 
		 << " is: " << average;
	
	system("pause");
	return 0;

}
Any help would be appreciated!
when I input 5 I get 2.5 so I assume your calculations are correct. However, You should be checking the number before using it.

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
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <limits>
#include <cstdlib>
using namespace std;

int main(){

	double n, var, sum = 0, average;
	cout << "Enter positive integer N: " << flush;
	while (!(cin >> n))
	{
		cin.clear();
		cin.ignore(numeric_limits<streamsize>::max(), '\n');  //ignores all characters until a newline
		cout << "Bad input. Try again." << endl;
		cout << "Enter positive integer N: " << flush;
	}
	cin.ignore(numeric_limits<streamsize>::max(), '\n');

	
	//exits program if a negative number is entered
	if (n < 0)
	{
		cerr << "Negative numbers are not allowed program terminated" << flush;
		cin.ignore(numeric_limits<streamsize>::max(), '\n');
		exit(EXIT_FAILURE);
	}
	
	var = n;

	for (int x = 0; x <= var; x++)
	{
		sum = sum + n;
		var = (var - 1.0);
		average = sum / (n + 1.0);

	}



	cout << "The mean of all integers from 0 to " << n
		<< " is: " << average;

	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	return 0;

}


When I enter 8, I get 4.444 but it should be 4. Why is that?

@Yanson Thank you.
try this for your loop
1
2
3
4
5
6
7
8
	var = n;
	int x = 0;
	for (x = 0; x <= var; x++)
	{
		sum = sum + x;
	}
	average = sum / x;
@Yanson Yes, that works! Thank you so much.
Topic archived. No new replies allowed.