Reputation: 75
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
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:
if
s and use a switch
. 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. a
, s
, m
or d
, your code silently exits. You should display something like "Invalid input." A
vs a
. Upvotes: 7
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:-
Upvotes: 0