English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

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?

2007-02-03 05:18:51 · 4 answers · asked by John H 2 in Computers & Internet Programming & Design

How can I use an if then statement to catch the divide by zero?

2007-02-03 05:32:29 · update #1

4 answers

You can't divide by zero. You could put an If then statement to catch the div by zero and give the appropriate value

2007-02-03 05:24:59 · answer #1 · answered by Brian 5 · 0 0

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);
}

2007-02-03 13:25:09 · answer #2 · answered by rongee_59 6 · 0 0

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.

2007-02-03 13:25:20 · answer #3 · answered by D 4 · 0 0

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.

2007-02-03 13:44:21 · answer #4 · answered by Anonymous · 0 0

fedest.com, questions and answers