Kester Allen | 6 Apr 2006 18:42
Picon

Re: [QUIZ] Perl 'Easy' Quiz of the Week #2006-04-02 - Rounded Fractions

Here's my solution:

#!/usr/bin/perl

use strict;
use warnings;

eval {
    main ();
};
if ( my $err = $ <at>  ) {
    print STDERR "# $0: $err\n";
    exit 1 ;
}
exit 0;

sub main {
    my $in_frac1 = shift  <at> ARGV or die "need two inputs";
    my $in_frac2 = shift  <at> ARGV or die "need two inputs";

    my $dec1 = frac2dec( $in_frac1 );
    my $dec2 = frac2dec( $in_frac2 );
    my $frac = dec2frac( $dec1 * $dec2 );

    print "$in_frac1 X $in_frac2 = $frac\n",
          "$dec1 X $dec2 = ", $dec1 * $dec2, "\n";
}

sub dec2frac {
    my $dec = shift () or die "no input in dec2frac";
(Continue reading)

Sven Hergenhahn | 5 Apr 2006 09:05
Picon

Re: [QUIZ] Perl 'Easy' Quiz of the Week #2006-04-02 - Rounded Fractions

Hi All,

Here's my suggestion.

Cheers,
Sven

#!/usr/bin/perl -w
#
# Name:         quiz_fractions.pl
#
# Description:   Your task: create a script that prompts for a ratio of two integers and a quantity 
#                given as a whole number and/or a fraction (e.g. "1 3/5", "12", "3/7") and print out 
#                a rounded result of multiplying the quantity by the ratio in the same format.
#
#                The result should be rounded to the nearest half, third, or fourth, whichever is most 
#                accurate (in cases exactly between two quantities, using the lowest denominator).  You 
#                may assume none of the integers are overly large.
#
# Author:       Sven Hergenhahn
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

use strict;

# set a lookup hash for the remainder
my %fractions = (0 => '0', 1/4 => '1/4', 1/3 => '1/3', 1/2 => '1/2', 2/3 => '2/3', 3/4 => '3/4', 1 => '1');

# Get input (not checked here!)
print 'Please enter a fraction: ';
my $frac_in = <STDIN>; chomp $frac_in;
(Continue reading)


Gmane