Ruby simple math outputs 0.0 every time

Viewed 48

recently I have started writing the same thing (bmi calculator) in many languages. And I got stuck in ruby. Everything is done, but simple math problem always outputs 0.0. I tried researching the problem, but I couldn't find anything similar in ruby.

Here is my code:

print 'Weight: [lbs/kg] '
w = gets.to_f
print 'Height: [in/m] '
h = gets.to_f
    
print 'Choose your measurement system: [I/M] '
mSys = gets.to_s

if mSys == 'i' || mSys == 'I'
    bmi = 703 * (w / (h**2))         # Problem is here

elsif mSys == 'm' || mSys == 'M'
    bmi = w / ((h)**2)               # And here.
end

bmi = bmi.to_f
puts bmi

if bmi < 18.5
    puts 'Consider eating few burgers.'

elsif bmi > 18.5 && bmi < 25
    puts 'You have nothing to worry about.'

elsif bmi > 25
    puts 'Great Council of BMI says You are overwieght!'
end
1 Answers

The bmi is never calculated.

You lack an else clause on your bmi calculation. If we add one in and examine mSys...

if mSys == 'i' || mSys == 'I'
  bmi = 703 * (w / (h**2))
elsif mSys == 'm' || mSys == 'M'
  bmi = w / ((h)**2)
else
  p "#{mSys}"
end

We get "i\n". You need to strip the newline.

mSys = gets.chomp

Note there's no need for a to_s, gets already returns a String.


The more Rubyish way to write your logic would be to use case, snake case, clear variable names, and constants.

BMI_CONVERSION_FACTOR = 703

bmi = case measurement_system.downcase
when 'i'
  BMI_CONVERSION_FACTOR * (w / (h**2))
when 'm'
  w / (h**2)
else
  raise "Unknown measurement system: #{measurement_system}"
end
Related