median not showing up as a decimal

my median is never a decimal for some reason how can i fix it show it shows up as decimal at appropriate times.

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
using namespace std;

const int N=10;

void input(double &s, int arynum[]){
    s=0;
    for (int i = 0; i<N; i++){
    cout<<"Grade "<<i+1<<" ";
    cin>>arynum[i];
    s= s+arynum[i];
    }


}


void swap(int &a, int &b){
    int temp;
    temp=a;
    a=b;
    b=temp;
}


void sort(int arynum[]){

    for (int a=0; a<N; a++){

        for (int b=0; b<N; b++){

        if (arynum [a]>arynum[b]){
            swap (arynum[a], arynum[b]);

}

}

}


}

double calc (double sum, int arynum[]){
    double mean=sum/N;

}





void output(double sum, int arynum[]){

cout<<"Your mean is: "<< sum/N <<endl;

for (int a=0; a < N; a++)
   {
       cout << arynum[a] << " " ;
   }

}



int main(){

    int numbers[N];
    double mean;
    double n;
    double s;
    input(s, numbers);
    sort(numbers);
    output(s, numbers);
    int size = sizeof(numbers)/sizeof(int);
    double median = size % 2 ? numbers[size / 2] : (numbers[size / 2 - 1] + numbers[size / 2]) / 2;
    cout<<"Your median is " <<median <<endl;




}



numbes is an array of int. Any int divided by an int gives an int.

What is 3/2? One. What is 6/8? Zero.

Don't divide an int by an int if you want a decimal answer.
If you divide by 2.0 rather than just 2, the compiler will use double arithmatic for the division. Or use a double cast on one of the operands.

Andy

PS Why are you using this?

int size = sizeof(numbers)/sizeof(int);

It will just return the N you used to create the array. So you might as well use N rather than size (as you are everywhere else).
Last edited on
what do you mean by double cast on operands? sorry i am new to c++
casting in C and C++ is to take an object of one type and turn it into another type. For your own classes you'd have to write the functionality yourself, but for simple primitives like int, it's part of the language.

To cast an int x as a double, you can use the C style:
(double) x
or the (safer) C++ style
static_cast<double> (x)

like this
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using std::cout;

int main(){
int x = 7;
double y0 = 8/x;
double y1  = 8/static_cast<double> (x);

 cout << "y0 = " << y0 << std::endl <<  "y1 = " << y1 << std::endl;
}
Last edited on
Or even a function-style cast, e.g. double(x)
Thanks got it working now.
Topic archived. No new replies allowed.