1 year ago
#386284
Coral Beaches
Counters in a loop are counting much larger than expected
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.
c++
loops
counter
0 Answers
Your Answer