형식화된 출력
Coddy Ruby 여정의 기초 섹션에 포함된 레슨 — 88개 중 38번째.
챌린지
쉬움이전 레슨에서 모든 계산 기능이 포함된 더치페이 계산기(Bill Split Calculator)를 완성했습니다. 이제 루비(Ruby)의 문자열 포매팅을 사용하여 금액을 소수점 둘째 자리까지 정확하게 표시하도록 출력 형식을 개선해 보겠습니다.
달러 금액을 표시하는 출력 라인을 수정하여 % 연산자와 함께 포맷 문자열을 사용하세요. 루비에서는 %.2f를 사용하여 숫자를 소수점 둘째 자리까지 형식을 지정할 수 있습니다.
모든 금액 수치에 대해 소수점 둘째 자리까지 정확히 표시되도록 다음 출력 라인들을 업데이트하세요:
Bill: $[bill]Tip amount: $[tip_amount]Total with tip: $[total]Each person pays: $[per_person]
각 금액 수치의 형식을 지정하려면 % 연산자를 사용하세요. 예를 들어, "%.2f" % value는 숫자를 소수점 둘째 자리까지 포맷합니다.
예를 들어, 입력값이 85.50, 18, 3인 경우 전체 출력은 다음과 같아야 합니다:
Welcome to the Bill Split Calculator!
Let's split your bill fairly.
Bill: $85.50
Tip: 18%
People: 3
Tip amount: $15.39
Total with tip: $100.89
Each person pays: $33.63참고: 팁 백분율과 인원수는 소수점 포맷 없이 정수로 유지되어야 합니다 (뒤따르는 0을 피하기 위해 %g를 사용하세요).
직접 해보기
# TODO: Write your code below
# Use puts to display the welcome message
puts "Welcome to the Bill Split Calculator!\nLet's split your bill fairly."
# Read user inputs
bill = gets.chomp.to_f
tip_percent = gets.chomp.to_f
people = gets.chomp.to_f
# Display confirmation message
puts "Bill: $%g" % bill
puts "Tip: %g%%" % tip_percent
puts "People: %g" % people
# Calculate tip amount and total
tip_amount = bill * tip_percent / 100
total = bill + tip_amount
# Display calculation results
puts "Tip amount: $%g" % tip_amount
puts "Total with tip: $%g" % total
# Calculate per person amount
per_person = total / people
# Display per person amount
puts "Each person pays: $%g" % per_person