拆分不同的数字,计算每个事件的出现次数和返回百分比

时间:2018-10-13 17:11:51

标签: perl

我想拆分用户输入的数字并将其拆分为perl中的列表,并返回按拆分数字排序的计数和百分比:

例如,用户在stdin中输入:112219992221474774

数字1为4,占22.22%

数字2为5,占27.77%

数字4为3,占16.67%

数字7为3,占16.67%

数字9为3,占16.67%

到目前为止我做了什么?

use strict;
use warnings;

sub main {

    print ("Enter the numbers: ");
    chomp(my $num = <STDIN>);

    my @Array = split (//, $num);

    my %numbers;
    $numbers{$_}++ for split / /, $Array[0];

    my $total;

    while (my ($k, $v) = each %numbers){
        $total += $v;
        print "Num $k are $v with $v/$total %\n";   
    }

}

main();

当我运行它时,我得到:

  

数字1为1且具有1/1%

任何线索为什么会这样?

1 个答案:

答案 0 :(得分:2)

您使用空字符串//正确分割了输入字符串,它返回该字符串中的字符列表;在这种情况下,您需要的数字。为什么然后再次按空间拆分@Array的第一个元素?这导致您的%numbers(1 => 1)

split //返回数字列表时,只需对其进行计数即可。

use warnings;
use strict;
use feature 'say';

while (1) {
    print "Enter the number: ";

    my $num = <STDIN>;
    chomp $num;
    if ($num =~ /[^0-9]/) {
        say "Non-digit(s) in input $num. Please try again.";
        next;
    }

    my @digits = split //, $num;   #/

    my %freq;
    ++$freq{$_} for @digits;

    for (sort keys %freq) { 
        say "Num are $freq{$_} with ", (sprintf "%.2f%%", ($freq{$_}/@digits)*100) 
    }
}

使用Ctrl-C退出。输入112219992221474774,输出为

Num 1 are 4 with 22.22%
Num 2 are 5 with 27.78%
Num 4 are 3 with 16.67%
Num 7 are 3 with 16.67%
Num 9 are 3 with 16.67%