我正在学习Perl并遇到过这个问题
编写一个读取两个数字并执行以下操作的Perl程序:它打印错误:如果第二个数字为0,则不能除以零.
如果我输入第二个数字为零,我收到一个错误
Illegal division by zero at ./divide.pl line 13, <STDIN> line 2.
我正在使用以下代码
#!/usr/bin/perl
## Divide by zero program
print("Enter the first number: \n");
$input1 = <STDIN>;
chomp ($input);
print ("Enter the second number: \n");
$input2 = <STDIN>;
chomp ($input2);
$answer = $input1/$input2;
if ($input2 == 0)
{
print("Error: can't divide by zero \n");
}
print("The answer is $answer \n");
Run Code Online (Sandbox Code Playgroud)
在进行划分之前,您需要执行检查.如果检查结果为真,您还需要完全跳过除法.
if ($input2 == 0) {
print("Error: can't divide by zero\n");
} else {
my $answer = $input1/$input2;
print("The answer is $answer\n");
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,总是use strict; use warnings qw( all );在你的程序中使用.