Jump to content

Spare change calculator


Menzo999

Recommended Posts

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;

}

 

Link to comment
Share on other sites

Try

$amount = 28;

$change = calcChange($amount);

foreach ($change as $v => $n) {
    echo "$n &euro;$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 by Barand
typo
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.