Menzo999 Posted May 22, 2021 Share Posted May 22, 2021 Hi! Need some help with a piece of code. New to this, so it is quite a pain in the ass! I need to make a code that shows the what spare change you should give back. so for example. when i put in 7 it should give back: 1 x 5 euro 1 x euro Which it does. but i have some trouble putting in the 1 euro's. for example when i put in 21 it gives back 2 x 10 euro Who can help me out? <?php function results($value) { if ($value >= 10) { echo floor($value / 10) . ' X 10 euro ' . PHP_EOL; $modulf = $value % 10; if ($modulf >= 5) { echo floor($modulf / 5) . ' X 5 euro ' . PHP_EOL; $modult = $modulf % 5; if ($modult >= 2) { echo floor($modult / 2) . ' X 2 euro ' . PHP_EOL; } } } else if ($value >= 5) { echo floor($value / 5) . ' X 5 euro ' . PHP_EOL; $modult = $value % 5; if ($modult >= 2) { echo floor($modult / 2) . ' X 2 euro ' . PHP_EOL; } } else if ($value >= 2) { echo floor($value / 2) . ' X 2 euro ' . PHP_EOL; } else if ($value >= 1) { echo floor($value / 1) . ' X 1 euro ' . PHP_EOL; } } if (count($argv) > 1) { $input = $argv[1]; if (!(is_numeric($input))) { echo 'Geen wisselgeld' . PHP_EOL; } else { $input = intval($argv[1]); if ($input !== 0) { results($input); } else { echo 'Geld wisselgeld' . PHP_EOL; } } } else { echo 'Geen wisselgeld' . PHP_EOL; } Quote Link to comment https://forums.phpfreaks.com/topic/312774-spare-change-calculator/ Share on other sites More sharing options...
Barand Posted May 22, 2021 Share Posted May 22, 2021 (edited) Try $amount = 28; $change = calcChange($amount); foreach ($change as $v => $n) { echo "$n €$v coins <br>"; } function calcChange($amt) { $coins = [ 10 => 0, 5 => 0, 2 => 0, 1 => 0 ]; foreach ($coins as $v => &$n) { $n = intdiv($amt, $v); $amt -= $n * $v; } return $coins; } Edited May 22, 2021 by Barand typo Quote Link to comment https://forums.phpfreaks.com/topic/312774-spare-change-calculator/#findComment-1586727 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.