July 2011
Intermediate to advanced
400 pages
8h 46m
English
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, ...
Read now
Unlock full access