Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

مخرجات منسقة (sprintf)

جزء من قسم Fundamentals في رحلة R على Coddy — الدرس 37 من 78.

challenge icon

التحدي

سهل

في الدرس السابق، أكملت حاسبة تقسيم الفاتورة (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 = "")

جميع دروس Fundamentals