Hackerrank Day 2: Operators

Task
Given the mealCost, tipPercent (the percentage of the meal price being added as tip), and taxPercent (the percentage of the meal price being added as tax) for a meal, find and print the meal’s totalCost.

screen-shot-2016-12-09-at-10-59-06-am

My solution in Ruby: 

# gets user input and convert them to float

mealCost = gets.to_f
tipPercent = gets.to_f
taxPercent = gets.to_f

tip = mealCost * (tipPercent / 100.0)
tax = mealCost * (taxPercent / 100.0)

totalCost = (mealCost + tip + tax).round

puts “The total meal cost is #{totalCost} dollars.”

I made one seemingly minor but critical mistake when I first solved the problem.  I divided tipPercent and tax Percent by 100, instead of 100.0.  This does not yield the same result in codes because when the computer divides by an integer (whole number) and not a float (decimals), it rounds the result to the nearest integer (which in this case, 20/100 = 0).  To get a float as your results, you have to change the values in the math operation to floats as well.

Advertisements
Hackerrank Day 2: Operators

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s