C++ rounding errors

82 Views Asked by At

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;
}
1

There are 1 best solutions below

0
Izik Avinoam On

The main problem that can cause this is that you are not initializing the variables.

In the below code, I have fixed this and a few other things:

void plusMinus(const vector<int> &arr)
{
    float pos = 0.f;
    float neg = 0.f;
    float zero = 0.f;
    float arrsize = arr.size();

    for(auto &i : arr)
    {
        if(i == 0)
            zero++;
        else if(i < 0)
            neg++;
        else if(i > 0)
            pos++;
    }

    pos = pos/arrsize;
    neg = neg/arrsize;
    zero = zero/arrsize;

    cout << fixed << setprecision(6);
    cout << pos << endl;
    cout << neg << endl;
    cout << zero << endl;
}