如何在Perl中进行整数除法OR如何使二进制搜索工作? [英] How can I make integer division in Perl OR How can I make my binary search work?

查看:218
本文介绍了如何在Perl中进行整数除法OR如何使二进制搜索工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现二进制搜索。这是我的代码:

I'm trying to implement binary search. This is my code:

#!/usr/bin/perl
#use strict;
use warnings;

@array = (1..100);
$number = <STDIN>;
$low = 0;
$high = $#array;

while($low < $high){
    print "Searcing $low ---- $high \n";
    $mid = $low + ($high - $low)/2;
    if($array[$mid] == $number){
        print "Found in index:" . $mid;
        last;
    }
    elsif($array[$mid] < $number){
        $low = $mid + 1;
    }
    else{
        $high = $mid - 1;
    }   
}

但它虽然直截了当但不起作用实现(至少它将使用Java)。

似乎我在分割时得到浮点值而无法搜索。如果我提供输入 5 我得到垃圾:

But it does not work although it is a straight forward implementation (at least it would be in Java).
It seems that I get float values when dividing and can not search. If I provide as input 5 I get garbage:

5  
Searcing 0 ---- 99  
Searcing 0 ---- 48.5  
Searcing 0 ---- 23.25  
Searcing 0 ---- 10.625  
Searcing 0 ---- 4.3125  
Searcing 3.15625 ---- 4.3125  

如何使用整数数字,所以我可以索引数组?

此外,如果我取消注释使用严格我会收到以下错误。他们的意思是什么?

How can I make it use integer numbers so I can index the array?
Also if I uncomment use strict I get the following errors. What do they mean?

Global symbol "@array" requires explicit package name at D:\Development\Perl\chapter3\binarySearch.pl line 6.  
Global symbol "$number" requires explicit package name at D:\Development\Perl\chapter3\binarySearch.pl line 9.  
Global symbol "$low" requires explicit package name at 


推荐答案

您应该使用函数 int

除此之外,你需要使用strict; 并使用 my 来确定变量的范围。这将捕获您可能错过的错误。只需声明它们:

Aside from that, you need to use strict; and use my to scope your variables. This will catch errors that you might miss. Just declare them like this:

my @array = (1..100);
chomp(my $number = <STDIN>);
my $low = 0;
my $high = $#array;

my $mid = int ($low + ($high - $low)/2);

您可以考虑使用 chomp 也可以从输入中删除换行符。

You might consider using chomp too, to remove newlines from your input.

这篇关于如何在Perl中进行整数除法OR如何使二进制搜索工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆