在下面的Perl程序中,由于某种原因,整数除法不会发生。相反,控制台输出两个整数的连接,也不会发生divsion的if语句。为什么是这样?感谢。
代码:
print "Please Enter Your First Number\n";
$num1 = <>; chomp $num1;
print "Please Enter Your Operation\n";
$operation = <>; chomp $operation;
print "Please Enter Your Second Number\n";
$num2 = <>; chomp $num2;
if ($operation == "+"){
$result = $num1 + $num2;
} elsif ($operation == "-"){
$result = $num1 - $num2;
} elsif ($operation == "*"){
$result = $num1 * $num2;
#Problem HERE:
} elsif ($operation == "/"){
if ($num2 == 0){
print "Cant Divide be Zero Mate\n";
} else {
$result = $num1 / $num2;
}
}
print "\n";
print "result of $num1 $operation $num2 = $result";
答案 0 :(得分:8)
使用 eq 代替 == 进行字符串比较。
print "Please Enter Your First Number\n";
$num1 = <>;
chomp $num1;
print "Please Enter Your Operation\n";
$operation = <>;
chomp $operation;
print "Please Enter Your Second Number\n";
$num2 = <>;
chomp $num2;
if ( $operation eq "+" ) {
$result = $num1 + $num2;
}
elsif ( $operation eq "-" ) {
$result = $num1 - $num2;
}
elsif ( $operation eq "*" ) {
$result = $num1 * $num2;
}
elsif ( $operation eq "/" ) {
if ( $num2 == 0 ) {
print "Cant Divide be Zero Mate\n";
}
else {
$result = $num1 / $num2;
}
}
print "\n";
print "result of $num1 $operation $num2 = $result";
输出:
Please Enter Your First Number
6
Please Enter Your Operation
/
Please Enter Your Second Number
3
result of 6 / 3 = 2