Menu
Coddy logo textTech

형식화된 출력 (sprintf)

Coddy R 여정의 기초 섹션에 포함된 레슨. 78개 중 37번째.

challenge icon

챌린지

쉬움

이전 레슨에서는 모든 계산이 포함된 Bill Split Calculator를 완성했습니다. 이제 sprintf()를 사용하여 금액을 소수점 이하 정확히 2자리로 표시하도록 출력 형식을 개선하세요.

달러 금액을 표시하는 출력 줄을 수정하여 형식 지정에 sprintf()를 사용하세요. sprintf() 함수는 소수점 이하 2자리를 나타내는 %.2f를 사용하여 특정 소수 자릿수로 숫자를 형식화할 수 있습니다.

다음 출력 줄을 업데이트하여 모든 금액이 소수점 이하 정확히 2자리로 표시되도록 하세요:

  • Bill: $[bill]
  • Tip amount: $[tip_amount]
  • Total with tip: $[total]
  • Each person pays: $[per_person]

이전 레슨과 동일하게 산술식을 유지하세요: tip_amount <- bill * tip_percent / 100. 대신 tip_percent / 100을 곱하면 숫자를 소수점 이하 2자리로 반올림했을 때 1센트의 차이가 발생할 수 있습니다.

sprintf()를 사용하여 각 금액을 형식화하세요. 예를 들어 sprintf("%.2f", value)는 숫자를 소수점 이하 2자리로 형식화합니다.

예를 들어 입력값이 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 = "")

기초의 모든 레슨

직접 연습해 보세요: 온라인 R 컴파일러