Perl Fahrenheit到Celsius转换,反之亦然

时间:2012-10-19 08:16:19

标签: perl

我在Perl中有这个问题: 编写一个Perl脚本,询问用户的温度,然后询问是否要将其转换为Celius或Fahrenheit度。执行转换并显示答案。温度转换方程为:

1) Celsius to Fahrenheit:C=(F-32) x 5/9
2) Fahrenheit to Celsius:F=9C/5 + 32

我的脚本是:

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

print "Enter the temperature: ";
my $temp = <STDIN>;
print "Enter the Conversion to be performed:";
my $conv = <STDIN>;
my $cel;
my $fah;

if ($conv eq 'F-C') {

   $cel = ($temp - 32) * 5/9;
   print "Temperature from $fah degree Fahrenheit is $cel degree Celsius";
}

if ($conv eq 'C-F') {

    $fah = (9 * $temp/5) + 32;
    print "Temperature from $cel degree Celsius is $fah degree Fahrenheit"; 
}

从键盘输入$ temp和$ conv后,会出现空白输出。我哪里出错了?请帮忙。提前谢谢。

3 个答案:

答案 0 :(得分:2)

您没有考虑用户输入中的新行字符。

<STDIN>向其分配内容后,在每个标量上调用chomp

答案 1 :(得分:2)

输入后,变量中会有换行符。使用chomp来摆脱它。

然后会出现第二个问题 - 您在输出语句中使用$fah$cel。这应该是$temp变量,否则您将收到如下错误:

  

在连接(。)中使用未初始化的值$ cel或在...中使用字符串

以下是更新后的代码:

#!/usr/bin/perl
use strict;
use warnings;
print "Enter the temperature: ";
my $temp = <STDIN>;
chomp($temp);
print "Enter the Conversion to be performed:";
my $conv = <STDIN>;
chomp($conv);
my $cel;
my $fah;
if ($conv eq 'F-C')
{
 $cel = ($temp - 32) * 5/9;
 print "Temperature from $temp degree Fahrenheit is $cel degree Celsius";
}
if ($conv eq 'C-F')
{
 $fah = (9 * $temp/5) + 32;
 print "Temperature from $temp degree Celsius is $fah degree Fahrenheit"; 
}

答案 2 :(得分:0)

您也可以尝试Convert::Pluggable

use Convert::Pluggable;

my $c = new Convert::Pluggable;

my $result = $c->convert( { 'factor' => 'someNumber', 'from_unit' => 'C', 'to_unit' => 'F', 'precision' => 'somePrecision', } );
相关问题