NLP Learner in Switzerland

[C] Perfect Square Number ::: 제곱수 판별하기 본문

Algorithm in C/Exercise

[C] Perfect Square Number ::: 제곱수 판별하기

초코빵 2021. 3. 29. 06:07
728x90
반응형

 

 


까다로운 부분 알아가기


 

[1] true 또는 false를 반환하는 bool function 사용하기

▶ C library의 stdbool.h 헤더를 사용한다.

 

[2] 제곱수square number라는 조건은 어떻게 둘까?

▶ 특정 x의 제곱이 입력받은 수보다 작거나 같은 경우, 계속 x를 1씩 늘려가며 x를 찾는다.

 

[3] 함수에서 return이 한번 발생하면 그 다음 return은 수행되지 않는다.

 

[4] integer를 input으로 받을 수 있도록 한다.

▶ integer의 경우 data type은 int이며, format specifier는 %d를 사용한다.

▶ integer를 입력받을 경우에는, 변수명 앞에 &(ampersand)를 붙여 메모리의 주소(address of memory)를 가리킬 수 있도록 해야한다. 내가 이해한 내용이 맞다면, scanf는 '입력을 받는다' = '변화가능해야 함', 따라서 특정 수로 고정시키는 것이 아니라, 해당 변수가 들어가게 되는 메모리 주소자체를 가리킬 수 있도록 한다.

[5] "TRUE", "FALSE"라는 글자를 프린트해주어야 한다.

▶ bool function의 return은 1 또는 0이다. C언어는 파이썬과 달리 true와 false라는 글자는 이해를 못한다.

▶ 따라서 if statement로 true인 경우 "TRUE"를 출력할 수 있게 한다.

 

#include <stdio.h>
#include <stdbool.h> ------------------------ [1]

bool isPerfectSquare(int num){
    int i=1;
    while(i*i<=num){ ------------------------ [2]
        if(i*i==num){
            return true; -------------------- [3]
        }
        i++;
    }
    return false;
}
    
int main(){
    int num;
    printf("Enter an integer: ");
    scanf("%d",&num); ----------------------- [4]
    if(isPerfectSquare(num)){ --------------- [5]
        printf("Perfect Square Number: TRUE");
    }
    else{
        printf("Perfect Square Number: FALSE");
    } 
    return 0;
}

출력결과


 

Comments