-1

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;
}
8
  • your problem descripition seems to miss words. Eg "...though answers with absolute error of up to are acceptable." up to what? Commented Jan 30, 2024 at 9:02
  • please include input, output and expected output in the question Commented Jan 30, 2024 at 9:03
  • Please copy-paste the full and complete assignment text into your question. Commented Jan 30, 2024 at 9:03
  • 9
    You are using uninitialised values for pos, neg and zero. That's Undefined Behaviour, your program can do absolutely anything it wants. Commented Jan 30, 2024 at 9:08
  • 2
    You did NOT initialize your values you should initialize your values. C++ will not do that for you e.g.. float pos = 0.f; Commented Jan 30, 2024 at 9:09

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.