我想在没有除法运算符的情况下划分数字
def divede_me(val,ded)
i = 1; new_num=0
rem = val % ded
val = val - rem
while (val != new_num)
i += 1
new_num = ded * i
end
return i
end
p divede_me(14,4)
上面的脚本返回3但我也想要浮点数(例如3.5)以及编写上述脚本的最佳方法。
答案 0 :(得分:1)
def divide_me(val,ded)
i = 1; new_num=0
rem = val.to_f % ded
val = val - rem
while (val != new_num)
i += 1
new_num = ded * i
end
temp = 0.01
temp += 0.01 until ded * temp >= rem
return i + temp.round(2)
end
p divide_me(14,4)
=>3.5
p divide_me(15,4)
=>3.75
p divide_me(16,7)
=>2.29
扩展现有代码,这将使您获得相当准确的2位小数。删除.round(2)以查看不准确的浮动。
答案 1 :(得分:0)
这个逻辑可以帮到你
val = 14
ded = 4
r = val % ded
value = val -r
v_ck = 0
i = 0
while( value != v_ck )
i+=1
v_ck = ded * i
end
ded_ck = 0
j = 0
while(ded_ck != ded)
j += 1
ded_ck = r * j
end
puts i.to_s+"."+j.to_s