Testing a Condition: if..then

The problem with the simple tax calculator code shown earlier is that it accepts negative subtotals and calculates negative tax on them—a situation upon which the government is unlikely to look favorably! I therefore need to check for negative numbers and, when found, set them to zero. This is my new version of the code:

5taxcalculator.rb

taxrate = 0.175
print "Enter price (ex tax): "
s = gets
subtotal = s.to_f

if (subtotal < 0.0)  then
  subtotal = 0.0
end

tax = subtotal * taxrate
puts "Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}"

The Ruby if test is similar to an if test in other programming languages. Note, however, that the parentheses are once again optional, as is the keyword then. However, if you were to write the following, with no line break after the test condition, the then would be obligatory:

if (subtotal < 0.0) then subtotal = 0.0 end

Putting everything on one line like this adds nothing to the clarity of the code, which is why I tend to avoid it. My long familiarity with Pascal instinctively makes me want to add a then after the if condition, but because this really is not required, you may look upon this as a willful eccentricity of mine. The end keyword that terminates the if block is not optional. If you forget to add it, your code will not run.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.185.87