You could have the result as an unsigned short integer and use a flag to represent division by 0, keeping it all in a structure. That may be unnecessary but I think the solution is more elegant and sophisticated that way. I'm going to look into C++ programming again because I want to try out that idea.
I haven't touched C++ for almost a year now. I was halfway through a project in making a menu GUI library for the PSP. I gave up when I replaced the project with a python project.
It took me a while because I didn't know "Y" was different from 'Y'. The later being a char which is what I wanted but here it is.
Code: Select all
#include <iostream>
using namespace std;
struct divide_answer{
unsigned short int val;
bool nan;
};
divide_answer divide(unsigned short int x, unsigned short int y){
divide_answer ans;
if (y == 0){
ans.nan = true;
}else{
ans.nan = false;
ans.val = x/y;
}
return ans;
}
int main(){
unsigned short int x, y;
char leave_ans;
while(true){
divide_answer resultant;
cout << "Please enter number 1: ";
cin >> x;
cout << "Please enter number 2: ";
cin >> y;
resultant = divide(x,y);
if(resultant.nan){
cout << "Error: Cannot divide by 0";
}else{
cout << x << " / " << y << " = " << resultant.val;
}
cout << "\n";
while(true){
cout << "Do you wish to leave? (Y/N): ";
cin >> leave_ans;
if(leave_ans == 'Y'){
exit(0);
}else if(leave_ans == 'N'){
break;
}
}
}
}
To show you how much easier python is at the same thing:
Code: Select all
def divide(x,y):
if y == 0:
return False
else:
return x/y
while 1:
num1 = raw_input("Please enter number 1: ")
num2 = raw_input("Please enter number 2: ")
ans = divide(int(num1),int(num2))
if ans:
print num1 + " / " + num2 + " = " + str(ans)
else:
print "Error: Division by zero not possible."
while 1:
ans = raw_input("Do you wish to leave? (Y/N): ")
if ans == "Y":
raise (SystemExit)
elif ans == "N":
break
It does pretty much exactly the same thing.