gpt4 book ai didi

Perl 除法程序

转载 作者:行者123 更新时间:2023-12-01 08:22:50 25 4
gpt4 key购买 nike

我正在学习 Perl,遇到了这个问题

Write a Perl program that reads in two numbers and does the following: It prints Error: can't divide by zero if the second number is 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");

最佳答案

您需要在进行除法之前进行检查。如果检查为真,您还需要完全跳过除法。

if ($input2 == 0) {
print("Error: can't divide by zero\n");
} else {
my $answer = $input1/$input2;
print("The answer is $answer\n");
}

顺便说一句,总是总是使用 use strict;在你的程序中使用警告 qw(all);

关于Perl 除法程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49590411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com