Ex3 Floating point


#1

Hello,

I have searched but think I’m not asking the right question.

In exercise 3 of the ruby course, Study Drill 4 says to rewrite ex3.rb with floating point numbers.

I did some digging and found that to_f will output numbers in floating point (but I can’t figure out how to do it that way.)

I can also complete the exercise by writing each number as a floating point within the code.

Example: puts “Hens #{25.0 + 30.0 / 6.0}”

Is that what I was supposed to do or is there another way to output the numbers as floating point?

I tried to solve it myself, but think I might need a different way to ask the question. Or, maybe I’m just overthinking it…

I am very inexperienced.

Thanks,

Dan


#2

If I recall, there are several ways to tell ruby that a number or result is a float, otherwise you get some odd calculation results:

x = 5
=> 5

x / 2 
=> 2 

x / 2.0
=> 2.5

x / 2.to_f
=> 2.5

Dividing 5 by 2 initially gives a result of 2 as it is dealing in integers (both the inputs are integers). Clearly that is wrong, so you need to ensure one part of the equation is using float.

This can be achieved by adding some decimalisation (as you did above), or calling the ‘to_f’ method on the number with a period/full-stop.

I think you only need one part of the calc to be a float so have a play around with it.


#3

Are you familiar with exercise 3 in the ruby course? I’m wondering if there is another way that I was supposed to figure out, or if Zed meant for me to just use floats when I wrote the code.

Thanks,

Dan

edited: spelling error


#4

I just used floats in this exercise. Thought it was meant more like a “get used to type in code” exercise, and get familiar to floats etc.


#5

It’s ex3 so I wouldn’t be expecting too much more than formatting and basic syntax.

My point was you don’t have to decimalise every integer to get a float result.


#6

Hey @danbuffington, what @gpkesley wrote is pretty much it.