代码之家  ›  专栏  ›  技术社区  ›  tavalendo

拆分不同的数字,计算发生次数并返回每个数字的百分比

  •  1
  • tavalendo  · 技术社区  · 6 年前

    我想在perl中将用户输入的数字分割成一个列表,并返回按分割的数字排序的计数和百分比:

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

    数字1为4,占22.22%

    数字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();
    

    Num 1是1和1/1%

    你知道为什么会这样吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   zdim    6 年前

    使用空字符串正确拆分输入字符串 // @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) 
        }
    }
    

    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%