1

Perlに質問があります。ユーザーに温度を尋ね、次にそれを華氏または華氏に変換するかどうかを尋ねるPerlスクリプトを作成することです。変換を実行し、答えを表示します。温度変換の式は次のとおりです。

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を入力すると、空白の出力が表示されます。どこが間違っているのでしょうか。助けてください。前もって感謝します。

4

3 に答える 3

2

ユーザー入力に含まれる改行文字は考慮されていません。

chompから何かを割り当てた後、各スカラーを呼び出します<STDIN>

于 2012-10-19T08:20:27.807 に答える
2

入力後、変数に改行文字が含まれます。chompそれを取り除くために使用します。

次に、2番目の問題が発生します。出力ステートメントで$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"; 
}
于 2012-10-19T08:22:25.793 に答える
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', } );
于 2014-05-25T15:50:27.837 に答える