0

所以我知道Math.sqrt(number)Ruby 中的方法,但作为学习语言的一部分,我认为制作一些简单的函数是个好主意。我可能会从根本上找到平方根错误,但这就是我所做的:

def negative?(number)
  number < 0
end

@start = 2

def sqrt(number)
  if negative? number
    puts "Can't do negative"
  else
    if @start**2 < number
      @start += 0.01
      sqrt(number)
    else
      puts "Square root of #{number} is #{@start}!"
    end
  end
end

def start_sqrt
  print "Input text: "
  number = Integer(gets.strip)
  sqrt(number)
end

begin
  start_sqrt
rescue ArgumentError
  puts "Need a positive number!"
end

这适用于较小的数字,但是当我输入较大的数字时,如果我想得到答案,我需要更改 @start 的值,否则它会显示“堆栈太深”。我在代码中做错了什么,还是 Ruby 做的一切都很好,我只是要求它以资源密集型的方式找到数字的平方根?我想这可能不是一个编程问题,而是一个数学问题,因为我知道我可以这样做:

def sqrt(number)
  if negative? number
    puts "Can't do negative"
  else
    root = number**0.5
    puts "Square root of #{number} is #{root}!"
  end
end
4

1 回答 1

3

It looks like Ruby is working as expected. You are asking it to find the square root of a number in a resource-intensive way (recursion).

In fact, you have created a stack overflow error. :)

于 2012-08-09T16:28:58.983 回答