Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with places after the decimal.
Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to are acceptable.
Example
There are n=5 elements, two positive, one negative, and two zeros. Results are printed as:
0.400000 0.200000 0.400000
I am writing my solution in c++, appropriate functions to process user input are given.
here is my function, but I keep getting test cases wrong I'm assuming due to rounding errors but I'm not sure how to fix this if anyone can provide some insight, would be greatly appreciated!
void plusMinus(vector<int> arr) {
float pos, neg, zero, arrsize;
arrsize = arr.size();
for(int i=0; i< arr.size(); i++) {
if(arr[i] == 0)
zero++;
if(arr[i] < 0)
neg++;
if(arr[i] > 0)
pos++;
}
pos = pos/arrsize;
neg = neg/arrsize;
zero = zero/arrsize;
cout << fixed << setprecision(6) << pos << endl;
cout << fixed << setprecision(6) << neg << endl;
cout << fixed << setprecision(6) << zero << endl;
}
pos,negandzero. That's Undefined Behaviour, your program can do absolutely anything it wants.float pos = 0.f;