본문 바로가기

문제풀이/C 문제풀이

[HackerRank]Plus Minus

문제

Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.

Function Description
Complete the plusMinus function in the editor below. It should print out the ratio of positive, negative and zero items in the array, each on a separate line rounded to six decimals.

Input Format
The first line contains an integer, , denoting the size of the array.
The second line contains space-separated integers describing an array of numbers

Output Format
You must print the following lines:
A decimal representing of the fraction of positive numbers in the array compared to its size.
A decimal representing of the fraction of negative numbers in the array compared to its size.
A decimal representing of the fraction of zeros in the array compared to its size.

CODE

void plusMinus(int arr_count, int* arr) {
    int p = 0, m = 0, i; // 양수의 개수, 음수의 개수, for문의 인덱스 정의
    for (i = 0 ; i < arr_count ; i++) {
        if (*(arr+i) > 0) p++; // 양수의 개수 세기
        else if (*(arr+i) < 0) m++; // 음수의 개수 세기
    }
    printf("%f\n%f\n%f", (double)p/arr_count, (double)m/arr_count, 1-((double)(p+m)/arr_count));
// 비율 출력하기, 이 때 정수 나누기 정수이므로 double 로 형변환을 해줘야 실수로 출력된다.
}

감상

처음에 왜 안되는지 의문이었다. 형변환을 해야하는 문제도 오랜만에 보니까 새로웠다.

'문제풀이 > C 문제풀이' 카테고리의 다른 글

[HackerRank]Mini-Max Sum  (0) 2019.06.25
[HackerRank]Staircase  (0) 2019.05.26
[HackerRank]Diagonal Difference  (0) 2019.05.21
[Hackerrank]A Very Big Sum  (0) 2019.05.20
[Hackerrank]Compare the Triplets  (0) 2019.05.17