thermoplay
thermoplay

Reputation: 75

C++ Calculator, cannot divide 0 by itself

I have this problem, I would like to display that if 0/0, Output is that : "Cannot divide 0 by itself". How can I tweak my code so that I can display that output? If so, what code should I be using in order to make my goal come into fruition?
Here's my code below:

#include <iostream>
using namespace std;
double isAdd(double x, double y);
double isSub(double x, double y);
double isMult(double x, double y);
double isDiv(double x, double y);
int main() {
    cout << "Calculator\n";
    double oneV, twoV;
    char choice = 'a'; 
    cout << "Enter 2 Values : \n";
    cin >> oneV;
    cin >> twoV;
    cout << "Enter Operation to Use: ( a / s / m / d) \n";
    cout << "a = addition, s = subtraction, m = multiply, d = divide\n";
    cin >> choice; 
    if (choice == 'a') {
        cout << "The Sum is : " << isAdd(oneV, twoV);
    }
    if (choice == 's') {
        cout << "The Difference is : " << isSub(oneV, twoV);
    }
    if (choice == 'm') {
        cout << "The Product is " << isMult(oneV, twoV);
    }
    if (choice == 'd') {
        cout << "The Quotient is " << isDiv(oneV, twoV);
    }
}

double isAdd(double x, double y) {
    double answer = x + y;
    return answer;
}
double isSub(double x, double y) {
    double answer = x - y;
    return answer;
}
double isMult(double x, double y) {
    double answer = x * y;
    return answer;
}
double isDiv(double x, double y) {
        double answer = x / y;
        return answer;
}

Upvotes: 2

Views: 260

Answers (2)

3Dave
3Dave

Reputation: 29041

if ('d' == choice) {
    if (0 == twoV)
        //cout << "Cannot divide 0 by itself\n";
        cout << "Division by zero.\n";
    else
        cout << "The Quotient is " << isDiv(oneV, twoV);
}

Tips:

  • get rid of all of those ifs and use a switch.
  • Comparing to 0 will work in this case, but if you were working with a calculated value, you'd need to check for "nearly zero". See https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon . This is due to floating point precision limitations.
  • If the user enters something other than a, s, m or d, your code silently exits. You should display something like "Invalid input."
  • You're also not taking into account input case: ie, A vs a.

Upvotes: 7

Ayeshan Dissanayaka
Ayeshan Dissanayaka

Reputation: 11

if (choice == 'd')
{
    if (twoV == 0)
    {
        //this one for cannot dividing 0
        cout << "Undefined value (" << oneV << "/0)"<<endl;
    }
    else
    {
        //this one for normal other values
        cout << "The Quotient is " << isDiv(oneV, twoV);
    }
}

Tips:-

  • In here you use only conditional statements. But you can use switch case also. So, if you use them for implementing this it would be very attractive than using conditional statements. Refer them.

Upvotes: 0

Related Questions