Make variable recognize divide by 0

I need for the line that executes choice==Q to also know that when the user inputs 0 for num2 that it displays that you cant do that

#include <iostream>
using namespace std;

int main ()
{
int num1, num2, sum, difference, product, quotient, remainder;
char choice;

cout << "Enter two intergers: ";
cin >> num1;
cin >> num2;

cout << "(S)um " << endl;
cout << "(D)ifference " << endl;
cout << "(P)roduct " << endl;
cout << "(Q)uotient " << endl;

sum= num1 + num2;

difference= num1 - num2;

product= num1 * num2;

quotient= num1 / num2;

remainder= num1 % num2;


cout << "Please choose S, D, P, or Q: ";
cin >> choice;


if (choice=='S')
cout << num1 << " plus " << num2 << " is " << sum << endl;


else if (choice=='D')
cout << num1 << " minus " << num2 << " is " << difference << endl;


else if (choice=='P')
cout << num1 << " times " << num2 << " is " << product << endl;

else if (choice=='Q')
cout << num1 << " divided by " << num2 << " is " << quotient << " with a remainder of " << remainder << endl;


else
cout << "That was not a valid menu choice " << endl;



return 0;
}
Can't you literally just use an if statement to check if num2 is zero??
Put an if statement around are the quotient and only perform the division if num2 != 0.
Use an if to detect if num2 is zero and print "undefined" as the result.
Now whenever i enter zero at all the program completely crashes. any other ideas?
That is because you're doing the calculation without checking for zero.

1
2
3
4
5
6
7
8
9
sum= num1 + num2;

difference= num1 - num2;

product= num1 * num2;

quotient= num1 / num2;

remainder= num1 % num2;



These are basically lock stepping through the calculations. You don't need to actually store the result of these calculations.

 
cout << num1 << " plus " << num2 << " is " << num1 + num2 << endl;


You can use this idea as a starting point for the rest.
Last edited on
Sure you could filter the inputs, but what if the inputs are all constrained or calculated via other means and should return 0?

If you're debugging and trying to find which variable is affected and where the problem occurs you can use two methods:

1) Check if the variable is NaN (Not a Number):
1
2
3
4
5
template<typename T>
inline bool isnan(T value)
{
    return value != value;
}


2) If you're looking for infinity, you can try this one.
1
2
3
4
5
6
7
// requires #include <limits>
template<typename T>
inline bool isinf(T value)
{
    return std::numeric_limits<T>::has_infinity() &&
    value == std::numeric_limits<T>::infinity();
}


Note I believe the NaN one only work for floating point types (float, double).
Topic archived. No new replies allowed.