Perl Calculator,打印非复数,除以0错误

时间:2014-03-06 04:22:30

标签: perl

我不确定如何将此提示条件应用于我的代码: 例如: 根2 64 - 9 7 上面的例子会产生8和2.你的程序应该在单词exit作为运算符输入时结束。您的程序不应该处理复杂的数字,而是显示错误消息(即“请等待PerlCalculator的2.0版”)。此外,您的程序应显示除以0等错误。

到目前为止,这是我的代码:

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


print "enter a symbol operation symbol to and two numbers to make a calculation";

my $input = <STDIN>;

my ($operation, $x, $y) = split ' ', $input;
#print "$operation\n"."$x\n"."$y\n";
if($operation eq "+"){
my $z = ($x + $y);
print "$z\n";
print "$operation\n"."$x\n"."$y\n";
}
elsif ( $operation eq "-"){
my $z = ($x - $y);
print "$z\n";
print "$operation\n"."$x\n"."$y\n";
}
elsif ( $operation eq "*"){
my $z = $x * $y;
print "$z\n";
print "$operation\n"."$x\n"."$y\n";
}
elsif ( $operation eq "/"){
my $z = $x / $y;
print "$z\n";
print "$operation\n"."$x\n"."$y\n";
}
elsif ( $operation eq "%"){
my $z = $x % $y;
print "$z\n";
print "$operation\n"."$x\n"."$y\n";
}
elsif ($operation eq "pow"){
my $z = $x ** $y;
print "$operation\n"."$x\n"."$y\n";
print "$z\n";
}
elsif ($operation eq "root"){
my $z =  $x ** (1/2);
my $i =  $y ** (1/2);
print "$z\n";
print "$i\n";
print "$operation\n"."$x\n"."$y\n"; 
}
else{
print "$operation\n"."$x\n"."$y\n";
print " you messed up"."$operation\n/"; 
}

打印字符串在那里进行故障排除,以便我可以看到if语句是否采用了正确的整数

1 个答案:

答案 0 :(得分:0)

按零误差处理除法。

elsif ( $operation eq "/" ) {
    eval {
        my $z = $x / $y;
        print "$z\n";
        print "$operation\n" . "$x\n" . "$y\n";
    };

    if ($@) {
        warn "Error: Division by zero!!";
    }
}