두 수의 차

GOYENA·2025년 3월 27일

algorithm

목록 보기
2/12

1. 두 수의 차

https://school.programmers.co.kr/learn/courses/30/lessons/120803#qna

C언어는 처음이라 모르는데, 낯설다.
빼기 연산 문제는 쉽게 풀었다.
제한사항을 어떻게 적용하지?! 막혔다..

-50000 ≤ num1 ≤ 50000
-50000 ≤ num2 ≤ 50000

😇C언어 제한사항으로 검색해서 if문으로 제한사항 적용하는 법 알아냄
%d, %d로 매개변수 num1, num2를 받아오고, if문의 조건 참이라면 answer을 return함.

scanf("%d %d", &num1, &num2);
    if(-50000<=num1 && num1<=50000 && -50000<=num2 && num2<=50000)

scanf 함수 찾아보고 변수 바꿔서 성공!
&& - 논리연산자 and

2. 나이 출력

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

int solution(int age) {
    int answer = 2023-age;
    scanf("%d %d", &age, &answer);
    printf("2024년 기준 %d살 %d년생입니다.",age,answer);
    return answer;
}

"2022년 기준 40살이므로 1983년생입니다."

이 문장을 출력하기 위해 어떻게 해야하지?!!

C언어 입력, 출력검색해서 해결!
scnaf함수로 입력값을 받고, printf함수로 출력하는 방법 검색해서 성공!
scanf함수와 printf함수 학습!
계속 적용해봐야지.

3. 숫자 비교

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

int solution(int num1, int num2) {
   
    if (num1==num2){
        int answer = 1;
        scanf("%d %d %d", &num1, &num2, &answer);
        printf("num1이 %d이고 num2가 %d이므로 같습니다. 따라서 %d를 return합니다.",num1,num2,answer);
        return answer;}
        
    else{
        int answer = -1;
        scanf("%d %d %d", &num1, &num2, &answer);
        printf("num1이 %d이고 num2가 %d이므로 다릅니다. 따라서 %d를 return합니다.",num1,num2,answer);
        return answer;}
        
}

if문 안에서 answer을 선언하고, return하는 방식.
이 방식밖에 생각나지 않았다.
그닥 마음에 들지 않는다. 굳이 저걸 두번이나 반복해야 하나? 비효율적이고 지저분한데..
그래서 다른 분들의 코드를 봤다.
if문 밖에서 int answer=0;으로 선언하고 if문 안에서 조건에 맞게 answer값을 변경했다.
그리고 마지막에 return!
아! 왜 저걸 생각 못했지?!! 상수가 아니면 변경 가능하잖아!!

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

int solution(int num1, int num2) {
    int answer = 0;
    if (num1==num2){
        answer = 1;
        scanf("%d %d %d", &num1, &num2, &answer);
        printf("num1이 %d이고 num2가 %d이므로 같습니다. 따라서 %d를 return합니다.",num1,num2,answer);
        }
        
    else{
        answer = -1;
        scanf("%d %d %d", &num1, &num2, &answer);
        printf("num1이 %d이고 num2가 %d이므로 다릅니다. 따라서 %d를 return합니다.",num1,num2,answer);
        }
        return answer;
}

이 코드가 훨씬 마음에 든다.

scanf, printf함수를 연습하고 싶어서 굳이 넣어서, 여전히 길지만 훨씬 깔끔해 졌다.
C언어에서 int는 상수선언이 아닌 변수선언! 그럼 상수선언은 어떻게 하지?!
💡const int 배움!
const int answer = 0; 으로 바꿔서 적용해보니까 에러뜨네 역시!
재미있다ㅎㅎㅎ!!!
포인트 상수도 있네
C언어에는 다양한 변수형태가 있으니 앞으로 찾아보면서 공부하자!

profile
헤헷

0개의 댓글