Eri Mendz wrote:
> Good day all,
> 
> Have here a temperature conversion program im trying to "perfect" but
> no chance, its not working right. The input validation portion is
> fine, im satisfied likewise with the conversion to celsius.  My
> problem is conversion to fahrenheit: the answer is not right so is
> the temp unit during printout. The problem must be obvious but i
> pick-up slow.  Can you help me out and guide me :-)
> 
> #!/usr/bin/perl -w
> use strict;
> 
> print "This is a temperature conversion program.\n";
> print "Enter temperature to convert(e.g., 100C, 212F): ";
> chomp(my $input = <STDIN>);
> if ($input =~ m/^([+-]?\d+)(\.{1}\d+)?[ ]?([cCfF])$/){        #validate
>     input format my $real_num = $1;
>     my $temp_unit = $3;
>     my ($in_c, $in_f) = ($real_num, $real_num);
>     if ($temp_unit eq 'C' or 'c'){
>       $in_f = ($real_num * 9 / 5) + 32;
>       printf "%.2f C is %.2f F\n", $real_num, $in_f;
>     } else {  #it must be F if not C
>       $in_c = ($real_num - 32) * 5 / 9;
>       printf "%.2f C is %.2f F\n", $real_num, $in_c;
>     }
> } else {
>     #input failed validation check
>     print "Error is detected in input\n";
>     print "input format is number, optional space then letter C or F,
>     case insensitive, in exact order\n";
>     print "Please check your input and try again.\n";
> }
> Staring at the code trying to debug i realize is no nice exercise.
> But i want to learn, so no excuse. TIA.

        I changed two points in your code:

m/^([+-]?\d+)(\.{1}\d+)?[ ]?([cCfF])$/
 to
m/^([+-]{0,1}\d+(\.\d{0,2}){0,1})\s*([CF])$/i
                                                          ^--- make it case
insensitive
                                                ^----^
                                                   |--- either CF
                                 ^-^
                                            |----- Zero or more spaces
                ^---------------^
                              |------ You can have one set of .nn one or two
digits
             ^-^
    ^-------^ |---One or more digits
          |----you can have one of them or none
Then I switched in portion for calculation of F to C:

 printf "%.2f C is %.2f F\n", $real_num, $in_c
to
 printf "%.2f F is %.2f C\n", $real_num, $in_c;

You also were not picking up the portion to the right of decimal point if
any was put in.

See what you think.

I will send you the code I ran ( w2k  ActivePerl 5.6.1 build 623)

Wags ;)


**********************************************************
This message contains information that is confidential
and proprietary to FedEx Freight or its affiliates.
It is intended only for the recipient named and for
the express purpose(s) described therein.
Any other use is prohibited.
****************************************************************


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to