How do I work out the range of user input? (min/max)

I am trying to extend this piece of code I have written by also working out the range of the 6 numbers entered, unfortunately I don't really know where to start other then knowing I need if/else statements. Also, what if the user inputs a negative number?

Thanks guys

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;

float main()
{
	float X1, X2, X3, X4, X5, X6;
	float mean;
	float StandardDeviation;
	cout<<"Enter the first number:";
	cin>>X1;
	cout<<"Enter the second number:";
	cin>>X2;
	cout<<"Enter the third number:";
	cin>>X3;
	cout<<"Enter the forth number:";
	cin>>X4;
	cout<<"Enter the fith number:";
	cin>>X5;
	cout<<"Enter the sixth number:";
	cin>>X6;

	mean=(X1+X2+X3+X4+X5+X6)/6;
	StandardDeviation = sqrt(((pow(X1-mean,2)) + (pow(X2-mean,2)) + (pow(X3-mean,2)) + (pow(X4-mean,2)) + (pow(X5-mean,2)) + (pow(X6-mean,2)))/5);
	cout<<"Mean ="<<mean<<endl;
	cout<<"StandardDeviation ="<<StandardDeviation<<endl;
	cin.get(); cin.get();
	return 0;
}
Last edited on
Your method of named variables is very unyieldy and rigid. Hard to change. This would be the time to learn arrays and loops.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const size_t N = 6;
float X[N] {};  // X is an array of N float values
float value;
size_t x = 0;
while ( x < N && std::cin >> value ) // x can get values 0, 1, 2, 3, 4, 5
{
  X[x] = value;
  ++x;
}
// x is now the number of input values.  0 <= x <= N

float sum = 0.0f; // We have seen 0 values yet, so their sum is 0.
for ( size_t y = 0; y < x; ++y )
{
  sum += X[y];
}

float mean = 0.0f; // Some dummy default in case we had no input.
if ( 0 < x )
{
  mean = sum / x;
}


Calculating StandardDeviation is obviously yet another loop.

You did ask about the min/max. Look at: http://www.cplusplus.com/reference/algorithm/min_element/
Can you see how std::min_element could operate?


PS. The standard requires that main() returns an int (not float). Furthermore, some OS assume the return value to be in range [0..127].
What you just typed means nothing to me, guess I still have a long way to go.
Topic archived. No new replies allowed.