# Thread: One more problem that needs help

1. ## One more problem that needs help

hey there again guys,
Sorry for the long post:
i'm trying to make a function that prints the 25th, 50th, and 75th percentile of an array of numbers..For example if the array is (3, 6, 7, 8, 8, 10, 13, 15, 16, 20) (its the same on the wikipedia article about percentiles)and i want to find the 25th percentile ,the function finds the position of that element and then the main prints the element (NOT the position of the element in the array) .In this case using the formula you get position = 2.5 (rounding up)=3 so its the 3rd element of the array which is 7.I'm assignig pos as an int so that when the formula gives 2.5 the function will return only 2 and because the elements are numbered arr0=3 arr1=6 arr2=7, main prints 7 which is the correct one.The thing is when i try to find the 50th percentile the formula gives 5.0 , the function returns 5 and main prints arr[5] = 10 whereas the correct one is one step backwards ( arr4 = 8 ). Any suggestions on how i can change the function?
Code:
```#include <stdio.h>

float percentile(float arr[],int N,int P)
{
int pos;
pos=(N*P/100);  // <-- Here's the formula
return arr[pos];
}
int main ()
{
float arr[100];
int c,n;
float x,y,z;

// Array declaration
printf("Enter the size of your array:\n");
scanf("%d",&n);
printf("Enter the elements of your array:\n");
for(c=0;c<n;c++)
{
printf("Enter element assigned to arr[%d]: ",c);
scanf("%f",&arr[c]);
}
// Printing the percentiles
x=percentile(arr,n,25);
y=percentile(arr,n,50);
z=percentile(arr,n,75);
printf("\nPercentiles:\n");
printf("25th Percentile:   %.4lf\n50th Percentile:  %.4lf\n75th Percentile:  %.4lf",x,y,z);

return 0;
}```

2. Code:
`pos=(N*P/100);  // <-- Here's the formula`
The fact that integer division is truncated and results in the correct index is the bug, not the feature. The truncation is correcting for the zero-based nature of arrays. When no truncation occurs, you are one too high in the zero-based array.

Consider rounding the result up, and then subtracting one to normalize the value for the zero-based array.

Code:
```float percentile(float arr[],int N,int P)
{
float pos;
pos=(N*P/100.0);
pos = ceilf(pos);
return arr[(int)(pos) - 1];
}```

3. You can also do it in integers by adding 50 before dividing by 100.
Code:
```float percentile(float *a, int n, int p) {
return a[(n * p + 50) / 100];
}```

Popular pages Recent additions