본문 바로가기
Algorithm Study/Programmers

[프로그래머스] 옷가게 할인 받기 (C#)

by HanaV 2023. 8. 8.
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/120818

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

처음에 입력한 코드는 Convert.ToInt32를 사용하였다.

using System;

public class Solution {
    public int solution(int price) {
        if (price >= 500000) return Convert.ToInt32(price*0.8);
        else if (price >= 300000) return Convert.ToInt32(price*0.9);
        else if (price >= 100000) return Convert.ToInt32(price*0.95);
        else return price;
    }
}

하지만 이 코드로 제출을 했을 때 하나의 테스트 케이스를 자꾸 통과를 하지 못하였다.

그래서 그냥 (int)를 사용하니까 통과할 수 있었다.

using System;

public class Solution {
    public int solution(int price) {
        if (price >= 500000) return (int)(price*0.8);
        else if (price >= 300000) return (int)(price*0.9);
        else if (price >= 100000) return (int)(price*0.95);
        else return price;
    }
}

 

그래서 두 개의 차이점을 찾아봤다.

(int) 캐스팅

명시적 형 변환, 소수점 이하가 버려짐

Convert.ToInt32

소수점 이하 부분을 반올림해서 가까운 정수로 변환함

예를 들어 설명하자면,

Console.WriteLine((int)1000.5); -> 1000
Console.WriteLine(Convert.ToInt32(1000.5)); -> 1001

이 된다.

이 문제같은 경우에, 0.95를 곱해줄 때 소수점이 .5로 나올 때가 있다. 그래서 Convert.ToInt32를 하면 소수점이 .5인 경우에 올림이 되어서 테스트 케이스를 통과하지 못하였다.

문제 제한 조건이 중요한 이유 .. (제한 조건에 소수점 이하를 버리라고 되어 있다.)

728x90

"); wcs_do();