Click here to Skip to main content
15,910,603 members
Please Sign up or sign in to vote.
2.33/5 (3 votes)
See more:
I had a function:

double Normalize(double v, double c)
{
    return 1.0 / (1.0 - (v * v) / (c * c)); 
}


It worked correctly until I called it with zero argument by mistake:
double x = Normalize(2, 0);
Console.WriteLine(x);

It outputs 0, no exception. How come?! Everyone learned divide by zero is impossible. How can I be sure calculation is correct if there is division by zero in the middle?
Posted

When you passed the function (2,0) as arguments, you handed it int values and asked it to implicitly cast them to type double. The results are indeterminate, and there may be dangling non-zero bits in the LSB of the result. Squaring that value and dividing by it can produce any result, including 0 and infinity. If you pass the function (2.0, 0.0), which are explicit floating point values, I think you'll get the exception you're expecting.
 
Share this answer
 
Yo could separate the operations and then check if the division is Infinite

if(double.IsInfinity(down))
{
  //Exception
}


or validate this case, if your "c" is 0, then exception
 
Share this answer
 
Comments
programmer095 4-Jan-11 19:07pm    
Who will need to check infinity after every division?! With C++ there was exception -- all I need
Dalek Dave 5-Jan-11 5:13am    
That is what I would do, simple one-line check.
JF2015 5-Jan-11 5:19am    
Good one!
If you step through this code you will see (c * c), where c = 0, is -Infinity, not zero since you are using a floating-point type, double, as the data type. Change it int and it will throw the exception you expect.

http://msdn.microsoft.com/en-us/library/678hzkk9(v=VS.100).aspx[^]
 
Share this answer
 
v2
Comments
programmer095 4-Jan-11 19:08pm    
I see, thank you. My variable in real not int, it is double
We need to assign one if clause to spacify the condiction that if a user assign zero show the maassage like:

initialize the variable in public and write:

double x;
double y;
double z;
string op;


under oparent button we write:

x=system.convert.tostring(texbox?.text);
op=/;
if(y=0)
{
massagebox.show("can't be devided");
}


Safiullah
Afghanistan
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900