0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHP 自動販売機ロジック

Last updated at Posted at 2021-07-15

Every Qiita #13
のんびり独学初学者の毎日投稿チャレンジ 13日目
今回は・・・
自動販売機ロジックを考えたときの備忘録です。

処理内容

お釣りを貨幣毎に何枚必要かを計算し出力します。不足の場合不足金を出力します。

$purchase = 10000;   // 支払い金額
$product = 9000; // 購入金額
function calculation($purchase, $product){
  $money = [10000,5000,1000,500,100,50,10,5,1];
  $change = $purchase-$product;
  $result = [];
  if ($change < 0) {
	return $change *= -1;
  }
  foreach ($money as $value) {
    if($change <= 0){
      $result[$value] = 0;
    }else{
      $page = floor($change/$value);
      $result[$value] = $page; 
      $change -= ($page*$value);
    }
  }
  return $result;
}

返り値には貨幣をキーとして、値に対応する枚数を指定しています。

解説

  1. 貨幣の種類を格納した配列を用意します。
  2. お釣りを計算
  3. 返り値は配列になるので、空の配列を定義します。
  4. お釣りが0円未満の場合は-1を掛けてreturnします
  5. お釣りが0円以下の場合は枚数=0に設定し、全ての貨幣と枚数を出力できるようにします。
  6. お釣りを貨幣で割った整数値が枚数になるのでfloor関数で枚数を計算します。←そのまま返り値に格納します。
  7. 貨幣×枚数をお釣りから引き、お釣りを再定義します。

    ※4〜6を全ての貨幣でループ処理させます。
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?