My exercise is as follows: Given a list of N integers, find its mean (as a double), maximum value, minimum value, and range. Your program will first ask for N, the number of integers in the list, which the user will input. Then the user will input N more numbers.
Here is my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Input n: ";
cin >> n;
int first; //**LINE NUMBER 1**
cout << "No 1 is: ";
cin >> first;
int max = first;
int min = first;
for (int i=1; i<n;i++) //**LINE NUMBER 2**
{
int x;
cout << "No " << i+1 << " is: ";
cin >> x;
first = x; //**LINE NUMBER 3**
if (max < x)
{
max = x;
}
if (min > x)
{
min = x;
}
}
cout << "max is: " << max << endl;
cout << "min is: " << min << endl;
cout << "mean is: " << (double) (max+min)/2 << endl; //**LINE NUMBER 4**
cout << "range is: " << max - min << endl;
return 0;
}
However, the solution is a bit different:
For line number 1, it is
int first=0;
instead ofint first;
For line number 2, it is
for (int i=1; i<n;++i)
instead offor (int i=1; i<n;i++)
For line number 3, it is
first += x;
instead offirst = x;
For line number 4, it is
cout << "mean is: " << (double) first/n<< endl;
instead ofcout << "mean is: " << (double) (max+min)/2 << endl;
I tried some examples but both codes produce exactly the same results. Why is that? Or am I wrong somewhere?