Kaiton
Kaiton

Reputation: 33

Ruby Decimal Fractions

I am completly new to both programming and this forum. Today I wrote my very first script, and it works so far:

 def deltay(y2, y1)
  #puts "Delta y=#{y2 - y1}"
  y2 - y1
end

def deltax(x2, x1)
  #puts "Delta x=#{x2- x1}"
  x2-x1
end

def m(vardeltay, vardeltax)
  #puts "m=#{vardeltay / vardeltax}"
  vardeltay / vardeltax
end

def n(gradient, varx, vary)
 vary-gradient*varx
end

#activate the lines 21-25, when n is given.
#puts "Welcome to my linear function script. Please start with telling me your n:"

#print "> " ; n=STDIN.gets.to_i

#puts "So your n is #{n}."


puts "The first thing I need is your m.Please input your y2 then press RETURN and enter your y1:"
print "> " ; vary2=STDIN.gets.to_i ; vary1=STDIN.gets.to_i ; deltay(vary2, vary1) 

puts "Now, please input your x2 then press RETURN and enter your x1:"
print "> " ; varx2=STDIN.gets.to_i ; varx1=STDIN.gets.to_i ; deltax(varx2, varx1)

puts "\n"

puts "Your m equals #{m(deltay(vary2, vary1), deltax(varx2, varx1))}"

varm=m(deltay(vary2, vary1), deltax(varx2, varx1))

puts "So, now we need n. Your current equalation looks like this:y=#{varm}m+n"
puts "Lets insert your point, you gave me earlier : P(#{varx2}, #{vary2})"
puts "So, that is:"
puts "#{vary2}=#{varm*varx2}+n \nNow we going to perform |-#{varm*varx2}. And that equals #{n(varm, varx2, vary2)}"  ; n=n(varm, varx2, vary2) #{#{vary2-(varm*varx2)}=n" ; n=vary2-(varm*varx2)}

puts "So this is our equation so far:"
puts "f(x)=#{varm}x+#{n}"

puts "Now let's get to y, okay? So I need a value for x:"
print "> " ; varx=STDIN.gets.to_i ; puts "y=#{varm*varx+n}"

The problem is, if I insert negative integers(-1)/decimal fractions (1,2) for y2,y1,x2 or x1, it won't work correctly. Maybe my question is really stupid, but I didn't find anything helping my problem on the net.

Upvotes: 0

Views: 146

Answers (1)

Daniel Rikowski
Daniel Rikowski

Reputation: 72504

It looks like there are at least two problems in your code:

  1. You are parsing numbers using to_i. This method only returns integers ("to integer") and any fractional part is cut off. You can use to_f instead. (Or to_d if you decide to use BigDecimal instead of floating point numbers)
  2. It looks like you input decimal numbers using a comma (,) as decimal separator. You have to use a dot (.) instead.

PS: It helps if you tidy up your code a little bit. The mixing of calculations and string interpolations makes understanding the code unnecessarily hard. Same goes for putting multiple statements in a single line...

For example, this is hard to read, especially if you don't have smart syntax highlighting:

puts "Your m equals #{m(deltay(vary2, vary1), deltax(varx2, varx1))}"

This is better:

value_of_m = m(deltay(vary2, vary1), deltax(varx2, varx1))
puts "Your m equals #{value_of_m}"

Upvotes: 2

Related Questions