【PHP/演習問題】else if文[1]

【PHP/演習問題】else if文[1]

問題

お店のお会計で割引を適用するプログラムを作成してください。
なお、下記の条件を満たすものとします。

  • 合計金額は『単価×個数』で計算する
  • 単価は150円とする
  • 個数はコマンドライン引数で与える
  • 割引の条件
    10%OFF : 個数が5個以上
    20%OFF : 個数が10個以上
$ php practice.php 8 
割引金額         : 120円
合計金額(割引前) : 1200円
合計金額(割引後) : 1080円
$ php practice.php 12
割引金額         : 360円
合計金額(割引前) : 1800円
合計金額(割引後) : 1440円

解答例

<?php

// 個数
$unit = $argv[1];

// 単価
$price = 150;

// 合計金額(割引前)
$subtotal = $price * $unit;

// 合計金額(割引後)
$total = $subtotal;

// 割引金額
$discount = 0;

// 割引の適用
if( $unit >= 10 ) {
    $discount = $subtotal * 0.2;
    $total = $subtotal - $discount;
} else if( $unit >= 5 ) {
    $discount = $subtotal * 0.1;
    $total = $subtotal - $discount;
}

echo '割引金額         : '.$discount."円\n";
echo '合計金額(割引前) : '.$subtotal."円\n";
echo '合計金額(割引後) : '.$total."円\n";

?>