Ruby Decimal分数

时间:2014-09-02 19:10:12

标签: ruby function

我对编程和本论坛都不熟悉。今天我写了我的第一个脚本,它到目前为止起作用了:

 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}"

问题是,如果我为y2,y1,x2或x1插入负整数(-1)/小数分数(1,2),它将无法正常工作。也许我的问题真的很愚蠢,但我在网上找不到任何可以解决问题的方法。

1 个答案:

答案 0 :(得分:2)

您的代码中至少存在两个问题:

  1. 您正在使用to_i解析数字。此方法仅返回整数(“到整数”),并且任何小数部分都会被截断。您可以改用to_f。 (如果您决定使用BigDecimal而不是浮点数,则为to_d
  2. 看起来您使用逗号(,)作为小数分隔符输入十进制数字。你必须改为使用点(。)。
  3. PS:如果你整理一下你的代码会很有帮助。计算和字符串插值的混合使得对代码的理解变得不必要。同样可以将多个语句放在一行......

    例如,这很难理解,特别是如果你没有智能语法高亮显示:

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

    这样更好:

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