closest to the average

I wrote a program to get 10 numbers then find their average and then to cout the number that is closest to the average. for some reason when I entered ( 1.1 8.76 9.23 7.5 98.4 45 12.9 45.2 50 2.4) it gives out 28.049 which is the average but how is that possible what did I do wrong?

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
  #include <iostream>
using namespace std;
int main (){
	int i,j;
	float y,sum=0,min,x1,y1,x[10];
	for(i=0;i<10;i++){
		cin>>x[i];
		sum=sum+x[i];
	}
	y=sum/10;
	
	for(i=0;i<10;i++){
		x1=y-x[i];
		y1=y-x[i+1];
		if(y-x[i]<0){
			x1=x[i]-y;
		}
		if(y-x[i+1]<0){
			y1=x[i+1]-y;
		}
		if(x1>y1){
			min=x[i+1];	
		}
		else if(x1<y1){
			min=x[i];
		}
	}
	 cout<<min;

	return 0;
}
what did I do wrong

IMO, the first thing you did wrong was to use meaningless variable names. Using a bunch of single letter variable names, with the added bonus of having a variable that only differs by a numeric suffix is going to make following your logic difficult if not impossible.

The next thing is that you seem to have forgotten that there is such a thing as a space character. Again writing all of your formulas without any spaces makes reading the program more difficult.

Your program with a little whitespace added.

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
47
48
49
#include <iostream>

using namespace std;

int main()
{
    int i, j;
    float y, sum = 0, min, x1, y1;
    
    // Added this to avoid the typing, remove when progrem is working.
    float x[10] {1.1, 8.76, 9.23, 7.5, 98.4, 45, 12.9, 45.2, 50, 2.4}; 

    for(i = 0; i < 10; i++)
    {
        //cin>>x[i];
        sum = sum + x[i];
    }

    y = sum / 10;

    for(i = 0; i < 10; i++)
    {
        x1 = y - x[i];
        y1 = y - x[i + 1];

        if(y - x[i] < 0)
        {
            x1 = x[i] - y;
        }

        if(y - x[i + 1] < 0)
        {
            y1 = x[i + 1] - y;
        }

        if(x1 > y1)
        {
            min = x[i + 1];
        }
        else if(x1 < y1)
        {
            min = x[i];
        }
    }

    cout << min;

    return 0;
}


Another problem I notice is that you seem to be accessing your array out of bounds in several locations.


Topic archived. No new replies allowed.