[JS_오답노트]_거스름돈_실습

hanseungjune·2022년 6월 1일
0

JavaScript

목록 보기
66/87

문제

코드

function calculateChange(payment, cost) {
	let change = payment - cost;
    let fiftyCount = (change - (change % 50000)) / 50000;
    change = change - 50000 * fiftyCount;
    console.log(`50000원 지폐: ${fiftyCount}장`);

	let tenCount = (change - (change % 10000)) / 10000;
    change = change - 10000 * tenCount;
    console.log(`10000원 지폐: ${tenCount}장`);
    
    let fiveCount = (change - (change % 5000)) / 5000;
    change = change - 5000 * fiveCount;
    console.log(`5000원 지폐: ${fiveCount}장`);
    
    let oneCount = (change - (change % 1000)) / 1000;
    change = change - 1000 * oneCount;
    console.log(`1000원 지폐: ${oneCount}장`);
}

// 테스트 코드
calculateChange(100000, 33000);
console.log('');
calculateChange(500000, 378000);

요약

일단 틀림

몇 장 거슬러줄지는 몫으로 확인하고

거슬러주고 얼마 남았는지는 나머지로 확인한다

	let change = payment - cost;
	fiftyCount = (change - ( change % 50000 )) / 50000
    change = change - ( 50000 * fiftyCount )

위의 식 구조를 이해하면 관련된 다른 문제도 풀기 쉽지 않을까?

나머지와 몫!

참고코드 ( 함수 중첩 )

function calculateChange(payment, cost) {
 let money = payment - cost;
 function bild(amount){
  const count = Math.floor(money/amount);
  money = money - count * amount;
  console.log(`${amount}원 지폐: ${count.toFixed(0)}장`);
 }
 bild(50000);
 bild(10000);
 bild(5000);
 bild(1000);
}

// 테스트 코드
calculateChange(100000, 33000);
console.log('');
calculateChange(500000, 378000);
console.log('');
calculateChange(500000, 348000);
console.log('');
calculateChange(1200000, 218000);
console.log('');
calculateChange(1240000, 898000);
console.log('');
calculateChange(12312000, 898000);
console.log('');
calculateChange(12412310000, 898000);
profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글