Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Division Program

Tags:

perl

I'm learning Perl and have come across this question

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.

If I enter the second number as zero, I'm getting an error

Illegal division by zero at ./divide.pl line 13, <STDIN> line 2.

I'm using the following code

#!/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");
like image 585
Senthil Kumar Avatar asked Apr 02 '26 09:04

Senthil Kumar


1 Answers

You need to perform your check before doing the division. You also need skip doing the division entirely if the check is true.

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

By the way, ALWAYS ALWAYS use use strict; use warnings qw( all ); in your programs.

like image 123
ikegami Avatar answered Apr 04 '26 13:04

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!