CS 161 - Introduction to Programming with PHP

Solution: Assignment #3
 
<?php // Display how many of a denomination of $value will be returned as // change for $change, with the description of $single (when one) // or $plural (for multiple). Use $single.'s' if $plural not specified. // function changeBack($change, $value, $single, $plural='') { if ($plural=='') $plural=$single.'s'; // Default plural form $count=floor(($change+0.009)/$value); if ($count) { // Have at least one as change echo " $count ".($count>1?$plural:$single)."\n"; } return $change-$count*$value; } echo "Amount of purchase? "; $purchase=trim(fgets(STDIN)); if ($purchase<=0) { if ($purchase!='') { echo "I couldn't understand \"$purchase\" as an amount\n"; } else { echo "No purchase made; It's Miller Time.\n"; } exit; } echo "Amount of payment? "; $payment=trim(fgets(STDIN)); if ($payment<=0) { if ($payment!='') { echo "I couldn't understand \"$payment\" as an amount\n"; } else { echo "No payment? Get outa' here, ya lousy bum.\n"; } exit; } if ($payment<$purchase) { echo "You want to finance the rest of that, Buddy?\n"; } else if ($payment==$purchase) { echo "Exact change! Thank you!\n"; } else { echo "You get ".($payment-$purchase)." in change as:\n"; $change=changeBack($payment-$purchase,5.0,'five'); $change=changeBack($change,1.0,'dollar'); $change=changeBack($change,0.25,'quarter'); $change=changeBack($change,0.10,'dime'); $change=changeBack($change,0.05,'nickel'); $change=changeBack($change,0.01,'penny','pennies'); } ?>
Page last updated 17 October 2010