l.sch
l.sch

Reputation: 23

how to go around dividing by zero c++

I'm very new to programming having only started because of a class I have to take.

In the lab we have to program a simple calculator (adding, subtracting, division, and multiplication) and then plug in sets numbers the teacher gives us. Of course two of of the sets of numbers have zero in them. How would you code it to say undefined instead of saying floating point exception (core dumped)

#include <iostream>
#include <cmath>

using namespace std;

int main() {

    int a;
    int b;
    float c;
    float d;
    float e;
    float f;
    float g;
    float h;
    float i;
    float j;

    cout << "Enter value for a\n";
    cout << "Enter value for b\n";
    cout << "Then press return.\n";

    cin >> a;
    cin >> b;

    c = a + b;
    d = a - b;
    e = a * b;
    f = a / b;

    g = sqrt (c);
    h = sqrt (d);
    i = sqrt (e);
    j = sqrt (f);

    cout << a << " value for a\n";
    cout << b << " value for b\n";
    cout << "value for c is " << c << " \n";
    cout << "value for d is " << d << " \n";
    cout << "value for e is " << e << " \n";
    cout << "value for f is " << f << " \n";
    cout << "value for g is " << g << " \n";
    cout << "value for h is " << h << " \n";
    cout << "value for i is " << i << " \n";
    cout << "value for j is " << j << " \n";

    return 0;
}

Upvotes: 3

Views: 223

Answers (4)

Vikram Bhardwaj
Vikram Bhardwaj

Reputation: 127

you can use try catch (exception handling) if you know how to handle the exceptions or you can simply check if b == 0 then show your message instead of dividing the numbers.

Upvotes: 1

John Sensebe
John Sensebe

Reputation: 1396

If you store the condition you're interested in, you can easily refer to it in multiple places:

bool isDivisionByZero = (b == 0);
if (!isDivisionByZero) f = a / b; else f = 0;

...

if (!isDivisionByZero)
    cout << "value for f is " << f << " \n";
else 
    cout << "value for f could not be computed (division by zero) \n"

Upvotes: 0

TezlaCoil
TezlaCoil

Reputation: 134

Perhaps better, would be to sanitize your inputs. "If user input 0 for b, then say undefined, else, try to calculate."

You'll also run into the issue, of if a is less than b, the sqrt() function is going to throw an error as well (not designed to handle a negative input).

Upvotes: 2

Sam Orozco
Sam Orozco

Reputation: 1258

Just check before the division if either number is zero if(a == 0 || b == 0) f = 0;

Upvotes: 1

Related Questions