Coding Test/HackerRank

[HackerRank] Plus Minus c++

owls 2022. 7. 16. 21:49
728x90
  • 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  6 places after the decimal.

 

  • example

arr = [1,1,0,-1,-1]

There are  n = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000  and 1/5 = 0.200000. Results are printed as:

0.400000
0.400000
0.200000

 

  • sample input
STDIN           Function
-----           --------
6               arr[] size n = 6
-4 3 -9 0 4 1   arr = [-4, 3, -9, 0, 4, 1]
  • sample output
0.500000
0.333333
0.166667
  • explanation

There are 3 positive numbers, 2  negative numbers, and 1 zero in the array.
The proportions of occurrence are positive: 3/6 = 0.500000, negative: 2/6 = 0.333333 and zeros: 1/6 = 0.166667. 

 

  • solution

소수점 자릿수를 고정시키고 나누기한 결과를 출력하는 문제이다.

이 때 중요한 점은!

분수의 분모가 double로 되어 있어야 소수점으로 계산이 된다.

void plusMinus(vector<int> arr) {
    int plus = 0, minus = 0, zero = 0;
    for(auto &it : arr){
        if(it < 0)  minus++;
        else if(it == 0)    zero ++;
        else {
            plus++;
        }
    }
    
    double n = double(arr.size());
    double dp, dm, dz;
    dp =  plus / n;
    dm =  minus / n;
    dz =  zero / n;
    
    cout << fixed;
    cout.precision(6);
    cout << dp << endl;
    cout << dm << endl;
    cout << dz << endl;    
}

hackerrank plusminus solution c++

 

728x90