Thursday, July 30, 2009

What do you do if you need a number to be divided by 0 in Microsoft Visual C++ 6.0?

I have a program assignment that requires a number to be divided by zero, but the program says that it needed to close because of an error. What should I do?

What do you do if you need a number to be divided by 0 in Microsoft Visual C++ 6.0?
You can't divide by zero. You could put an If then statement to catch the div by zero and give the appropriate value
Reply:Division by zero is illegal in mathematics. It is undefined (just take a hand calculator and see what happens when you try to divide a number by zero. The calculator should display an 'E' somewhere meaning "error"). So anytime computer code comes across a computation where there is division by zero, it will error out and usually halt program execution. As the previous poster stated, programmers are supposed to add code to catch if the divisor is zero before doing the division, and if so, to error out gracefully (output an error message and branch around the division).





Example: Function SafeDivide()


Parameters:


   iDividend - number to be divided


   iDivisor - number that iDividend will be divided by.


   pAnswer - pointer where answer will be returned.


Return value:


   0 - Division was successful.


   1 - Error condition (division by zero).





int SafeDivide(double iDividend, double iDivisor, double *pAnswer)


{


   if(iDivisor == 0)


      return(1);





   *pAnswer = iDividend / iDivisor;


   return(0);


}
Reply:Either use try{ ...}catch(){ ... }... or catch it yourself before the division is done.





You would have something like this:





int a = 5;


int b = 0;





if (b == 0){


// error handling


}else{


double d = a/b;


}





Concerning try/catch: see Google for details.
Reply:Mathematically you cant divide by zero, if your program "requires" it, then you would need to put a try, throw, catch statement around the block of code that divides by zero in order to allow it.

carnation

No comments:

Post a Comment