The primary issue is in your use of x
while it is uninitialized leading to undefined behavior. Specifically, you declare x
as a value with automatic storage duration:
int i = 0, x;
Then on your first iteration through the loop, you encounter:
x = x + (i + 1);
Where the value of x
is accessed while it is uninitialized invoking undefined behavior. Lesson, always initialize your variables.
Next, you fail to validate the input of n
. You must validate all input to ensure a valid value is received, and especially where a numeric conversion is involved. You can use the failure to enter a numeric value as an indication the user is done entering values in this case, but if(n <= 0)
is insufficient in that case.
There is no real reason for x
to begin with. Your loop variable i
is declared prior to the loop and will survive the loop termination. You can simply use that to contain the number of values entered. You don't use average
anywhere except in output, so there is no need for it as a separate variable.
Taking that into consideration and addressing the other issues discussed above, and after checking Why is “using namespace std;” considered bad practice?, you could do something similar to:
#include <iostream>
int main()
{
float n = 0., sum = 0., minimum = 1., maximum = 0.;
int i = 0, init = 0;
std::cout << "enter numbers, any non-number when done:\n\n";
for (;; i++) /* loop continually incrementing i */
{
std::cout << "Enter number " << i+1 << " : ";
if (!(std::cin >> n)) {
break;
}
if (!init) { /* initialize min & max with 1st entry */
minimum = maximum = n;
init = 1;
}
sum += n; /* add n to sum */
if (n > maximum) { /* check/set new max */
maximum = n;
}
if (n < minimum) { /* check/set new min */
minimum = n;
}
}
if (init) { /* check if valid value received */
std::cout << "\nNo. values : " << i << "\n\n"
<< "Total = " << sum << '\n'
<< "Average = " << sum / i << '\n'
<< "Maximum = " << maximum << '\n'
<< "Minimum = " << minimum << '\n';
}
else {
std::cerr << "error: no valid input received.\n";
return 1;
}
}
(note: the use of the init
variable as a flag to indicate whether valid input has been received and to initialize maximum
and minimum
to the first value entered. There is only a single std::cout
needed for any one continual block of output -- regardless of how many lines are involved. See also C++: “std::endl” vs “\n” for subtle distinctions between the use of the two)
Example Use/Output
$ ./bin/sumavgmaxmin
enter numbers, any non-number when done:
Enter number 1 : 1.1
Enter number 2 : 2.2
Enter number 3 : 3.3
Enter number 4 : 4.4
Enter number 5 : done
No. values : 4
Total = 11
Average = 2.75
Maximum = 4.4
Minimum = 1.1
There a many ways you can approach this problem, but following from your start, this was a logical way to implement it.