Ferry fare total
The island ferry charges 12.50 for an adult ticket and 7.25 for a child ticket. Read how many adults and how many children are travelling and print the total fare. The amount must always show exactly two decimal places, so a total of thirty prints as 30.00.
Input
Two lines: the number of adults, then the number of children. Both are integers from 0 to 1000.
Output
One line: the total fare with exactly two digits after the decimal point and no thousands separator.
Example 1
Input
2 1
Output
32.25
2 x 12.50 + 1 x 7.25 = 32.25.
Example 2
Input
0 0
Output
0.00
Nobody travels, but the format still requires two decimals.
Constraints
- 0 <= adults, children <= 1000
- The total never exceeds 19750.00
Hints
Hint 1 of 3
Input arrives as text. Cast each line with (int) before multiplying.
Hint 2 of 3
sprintf('%.2f', $total) formats a number with exactly two decimals.
Hint 3 of 3
number_format() also works, but by default it inserts a comma every three digits; pass '.' and '' as the third and fourth arguments to turn that off.
Solution
Show a reference solution and explanation
<?php
$adults = (int) trim(fgets(STDIN));
$children = (int) trim(fgets(STDIN));
$total = $adults * 12.50 + $children * 7.25;
echo sprintf('%.2f', $total), "\n";
Why it works
Everything read from STDIN is a string, so (int) turns "2" into the integer 2 before any arithmetic. Multiplying an integer by a float such as 12.50 gives a float, and echo prints a float with at most 14 significant digits (the precision setting) and no trailing .0, which is why echo 30.0 shows 30. The task wants a fixed money format, so the value is passed through sprintf('%.2f'), which rounds to two decimals and pads with zeros. All the prices here are multiples of 0.25 and therefore exact in binary floating point; for real accounting code, keep amounts in integer cents to avoid rounding drift.
Lesson for this exercise: Variables and Types in PHP