본문 바로가기

프로그래머스/level 0

[C] 두수의 사칙연산

1. 두수의 합

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(int num1, int num2)
{
    int answer = -1;
    answer = num1+num2;
    return answer;
}
int answer = -1 이유 : 초기값 설정, 굳이 이렇게 안해도 됨

 

2. 두수의 차

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(int num1, int num2)
{
    int answer = 0;

    printf("num1, num2 입력 %d, %d\n", num1, num2);
    scanf("%d %d", &num1, &num2);

    answer = num1-num2;
    printf("%d", answer);
    return answer;
}
굳이 scanf를 고려하지 않았어도 됐다

 

3. 두수의 곱

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(int num1, int num2) {
    if((0<=num1<=100) && (0<=num2<=100))
    {
        int answer = num1*num2;
            return answer;
    }
변수 범위 지정

 

4. 몫구하기

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(int num1, int num2) {
    int answer = num1/num2;
    return answer;
}
변수의 범위를 정해주었으면 더 좋았을 거 같다. 
/ : 몫 연산, % : 나머지 연산

 

 

출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges