0

I'm working on a HackerRank challenge and I've been assigned to finish this problem:

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.

I came up with this code:

void plusMinus(vector < int > arr, int size) {
  int i, j, k = 0;
  int total = size;

  double ratio;

  while (total >= 0) {
    if (arr[total] <= 1) {
      i = i + 1;

    } else if (arr[total] >= 1) {
      j = j + 1;

    } else {

      k = k + 1;

    }

    total = total - 1;

  }

  cout << i << " " << j << " " << k << endl;

  ratio = i / size;

  cout << ratio << endl;

  ratio = j / size;

  cout << ratio << endl;

  ratio = k / size;

  cout << ratio << endl;

}

But whenever I go to run the code, this is the output:

Download 6 -4 3 -9 0 4 1

Your Output 32855668 32855499 0 5.47594e+06 5.47592e+06 0

Expected Output

Download 0.500000 0.333333 0.166667

The actual size of the array is 6, and I have verified that it is six at the beginning of the program. The problem must be in my while loop with the counters nested in the "if else" statements. I know the loop is not going to infinity because I have put a "cout" statement and seen it count down the loop iterations.

user438383
  • 5,716
  • 8
  • 28
  • 43
  • 4
    `i = i + 1;` invokes *undefined behavior* because you didn't initialize `i`. Same for `j` – UnholySheep Apr 07 '22 at 09:23
  • Side note: you have overlapping conditions: `<= 1` -> `== 1` won't ever be met within `>= 1` as the other branch has already been entered -> `>1` suffices. But then both conditions are complementary, thus either of the two `if`s *will* catch and the final else is *never* entered. If you have complementary conditions, don't repeat the second one, just have a single if-else. – Aconcagua Apr 07 '22 at 09:27

0 Answers0