Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby二进制搜索代码未返回预期结果_Ruby_Binary Search Tree - Fatal编程技术网

Ruby二进制搜索代码未返回预期结果

Ruby二进制搜索代码未返回预期结果,ruby,binary-search-tree,Ruby,Binary Search Tree,我试图用Ruby编写一个二进制搜索方法,但发现了一个奇怪的情况:当我在elsif语句中将两个数字相加并除以二时,我的代码没有返回我所期望的结果 当我给这个方法一个1-3的目标和一个[1,2,3,4,5,6,7,8,9,10]的数组时,这个方法工作了,我得到了我想要的目标的索引 当我给这个方法一个4的目标时,我得到了一个无限循环,因为middle=first+last/2代码返回的是5,而不是预期的3。我甚至试着打印一个7/2的结果,结果是3,但当它输入值时,返回5 当我给这个方法一个7-10的目

我试图用Ruby编写一个二进制搜索方法,但发现了一个奇怪的情况:当我在elsif语句中将两个数字相加并除以二时,我的代码没有返回我所期望的结果

当我给这个方法一个1-3的目标和一个[1,2,3,4,5,6,7,8,9,10]的数组时,这个方法工作了,我得到了我想要的目标的索引

当我给这个方法一个4的目标时,我得到了一个无限循环,因为middle=first+last/2代码返回的是5,而不是预期的3。我甚至试着打印一个7/2的结果,结果是3,但当它输入值时,返回5

当我给这个方法一个7-10的目标时,它会打断并说有一个未定义的方法“一个先决条件:

  • 4+4/2
    将为我们提供6。它相当于
    4+(4/2)
  • (4+4)/2
    将为我们提供4
这两种说法并不相同

关于两个中间计算:

middle=first+last/2
我们没有我们所期望的

您希望将
第一个
最后一个
除以二。 因此,您需要:

middle=(第一个+最后一个)/2
如果您将
first+last/2
替换为
(first+last)/2
,您的脚本将为我们提供:

binary_search(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
we're in the else and middle is now 2
we're in the elsif and middle is 3
we've found the target! middle is 3
 => true 

简单地列出你的期望值(即
给定我的_方法(arg1,arg2),我希望它返回N
,然后只列出那些,这将导致测试驱动开发。你说“它有效”,但没有说明你通过的案例的预期结果。啊,就是这样-谢谢!
binary_search(4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
we're in the else and middle is now 2
we're in the elsif and middle is 3
we've found the target! middle is 3
 => true