Question: Division by Zero Instructions Redo Programming Exercise 8 of Chapter 4 so that your program handles exceptions such as division by zero and invalid input.

Division by Zero

Instructions

Redo Programming Exercise 8 of Chapter 4 so that your program handles exceptions such as division by zero and invalid input.

Your program should print Division by zero when 0 is entered for a denominator.

divisionByZero.h:

#include

using namespace std;

int main()

{

int a,b;

cin>>a>>b;

int ans;

try

{

if (b==0) throw "Division by zero";

cout<<"Answer:"<

}

catch(const char* msg)

{

cerr << msg << endl;

}

return 0;

}

main.cpp:

#include

#include //this header is for conversion to float

#include "divisionByZero.h"

using namespace std;

int main() {

//using string variables to read input and convert numerator and denominator to float

string num,den;

float numerator, denominator;

//bool falgs to check user input is valid and and also if den is 0

bool bool_value, num_flag = false , den_flag = false;

//reading numerator

cout << "Please enter the numerator : ";

cin >> num;

numerator = atof(num.c_str());

cout << numerator<< endl;

//validating the read value of num

while(true)

{

//if valid then we will come out of loop

if(not(num != "0" && numerator == 0))

{

num_flag = true;

break;

}

else

{

//else we will read until user enters correct value

cout << "inavlid input ";

cout << "Please enter the numerator : ";

cin >> num;

numerator = atof(num.c_str());

cout << numerator<< endl;

}

}

//reading denominator as a string into variable den

cout << "Please enter the denominator : ";

cin >> den;

//converting to float

denominator = atof(den.c_str());

cout << denominator<< endl;

//validating user input same as numerator

while(true)

{

if(not(den != "0" && denominator == 0))

{

den_flag = true;

break;

}

else

{

cout << "inavlid input ";

cout << "Please enter the denominator : ";

cin >> den;

denominator = atof(den.c_str());

cout << denominator<< endl;

}

}

//calling checkDenominator method which is in divisionByZero.h file to check denominator value is 0 or not

bool_value =checkDenominator(denominator);

//if denominator is not zero then we will show division

if(bool_value == false )

{

cout <<"The value of numerator/denominator is : " <

}

}

task:

Division by zero error is shown

0 out of 1 checks passed. Review the results below for more details.

Checks

Test CaseIncomplete

Program produces error message

Input

3 0 / 1 

Output

 

Results

Division by zero

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!