LoginSignup
0
0

More than 1 year has passed since last update.

チラ裏。if,elseの問題

Posted at

問題
「ポイント付与サービスを考えます。
購入金額が999円以下の場合、3%のポイント
購入金額が1000円以上の場合、5%のポイント
このように付与されるポイントを出力するメソッドを作りましょう。

ただし誕生日の場合はポイントが5倍になります。
誕生日の場合はtrue, 誕生日でない場合はfalseで表します。
また、小数点以下をすべてのポイント計算が終わったあとに切り捨てましょう。

呼び出し方:
calculate_points(amount, is_birthday)」

step1
購入金額が999円以下なのかまたは1000円以上なのかを判断したいので、条件分岐後ポイント計算をした後に結果を変数pointに代入します。

qiita.rb
  if amount <= 999
    point = amount * 0.03
  else
    point = amount * 0.05
  end

step2
誕生日の場合は、直前で定義した変数pointに5をかける処理を行います。

qiita.rb
  if is_birthday
    point = point * 5
  end

step3
小数点以下を切り捨てたポイント数を出力させたいので、ポイント数の記述部分に'.floorメソッド'を使用。

qiita.rb
puts "ポイントは#{point.floor}点です"

最後に指定された呼び出し方に添って記述し、完了。

qiita.rb
def calculate_points(amount, is_birthday)
  if amount <= 999
    point = amount * 0.03
  else
    point = amount * 0.05
  end
  if is_birthday
    point = point * 5
  end
  puts "ポイントは#{point.floor}点です"
end

備忘録を兼ねているので、私の恥ずかしい初回回答も掲載。
反省しているので触れないでください、、、

qiita.rb
〜悪い例〜
def calculate_points(a,b)
  if b && a <= 999
    puts "ポイントは#{a * 0.03 * 5.floor}点です"
  elsif b && a >= 1000
    puts "ポイントは#{a * 0.05 * 5.floor}点です"
  elsif a <= 999
    puts "ポイントは#{a * 0.03.floor}点です"
  else
    puts "ポイントは#{a * 0.05.floor}点です"
  end
end
〜悪い例〜

以上

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