I am trying to calculate the percentiles of a given vector of numbers, therefore i try to interpolate between the values when there is no exact percentile in the list. I tried doing the code below but when i ask the program to print with cout <<k and cout<< p[k] it does not print anything, why is it happening? What’s wrong with the code?
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
vector<double> sort(vector<double>& v) {
vector<double> copy = v;
sort(copy.begin(), copy.end());
return copy;
}
vector<double> percentile(vector<double>& v) {
double t = v.size();
double iter = 100/t;
vector<double> c(t,0);
for (int i = 0; i<=t; i++) {
c[i] = iter*i;
}
vector <double> p(100,0);
for (int j = 0; j<t-1; j++) {
for (int k = c[j]; k<c[j+1]; k++) {
if (k-c[j] == 0) {
p[k]= v[j];
}
else {
p[k] = v[j]+(v[j+1]-v[j])/(k-c[j]);
}
cout << k << endl;
cout << p[k] << endl;
}
}
return p;
}
int main() {
vector<double> v {10, 12, 13, 15, 19, 22, 29, 33,
40, 43, 32, 31, 28, 32, 45, 65, 36, 19, 20, 15};
vector<double> v2 = sort(v);
vector<double> p = percentile(v2);
}