형식화된 출력 (sprintf)
Coddy R 여정의 기초 섹션에 포함된 레슨 — 78개 중 37번째.
챌린지
쉬움이전 레슨에서 모든 계산 기능이 포함된 더치페이 계산기(Bill Split Calculator)를 완성했습니다. 이제 sprintf()를 사용하여 통화 값을 소수점 둘째 자리까지 정확하게 표시하도록 출력 형식을 개선해 보겠습니다.
달러 금액을 표시하는 출력 라인을 수정하여 sprintf()를 사용해 형식을 지정하세요. sprintf() 함수를 사용하면 %.2f를 활용하여 숫자를 소수점 둘째 자리까지 특정 자릿수로 형식을 지정할 수 있습니다.
다음 출력 라인을 업데이트하여 모든 통화 값에 대해 소수점 둘째 자리까지 정확히 표시되도록 하세요:
Bill: $[bill]Tip amount: $[tip_amount]Total with tip: $[total]Each person pays: $[per_person]
각 통화 값의 형식을 지정하려면 sprintf()를 사용하세요. 예를 들어, sprintf("%.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참고: 팁 백분율과 인원수는 소수점 형식 없이 정수로 유지되어야 합니다.
직접 해보기
# TODO: Write your code below
# Use cat() to display the welcome message
# Remember to use \n for new lines
cat("Welcome to the Bill Split Calculator!\nLet's split your bill fairly.\n")
# Read user inputs
con <- file("stdin", "r")
bill <- as.numeric(suppressWarnings(readLines(con, n = 1)))
tip_percent <- as.numeric(suppressWarnings(readLines(con, n = 1)))
people <- as.numeric(suppressWarnings(readLines(con, n = 1)))
close(con)
# Display confirmation message
cat("Bill: $", bill, "\n", sep = "")
cat("Tip: ", tip_percent, "%\n", sep = "")
cat("People: ", people, "\n", sep = "")
# Calculate tip amount and total
tip_amount <- bill * tip_percent / 100
total <- bill + tip_amount
# Display calculation results
cat("Tip amount: $", tip_amount, "\n", sep = "")
cat("Total with tip: $", total, "\n", sep = "")
# Calculate per person amount
per_person <- total / people
# Display per person amount
cat("Each person pays: $", per_person, "\n", sep = "")