Java – why doesn’t 0.0F / 0.0F produce any runtime errors?
Recently I tested the following program & I expect runtime errors, but it displays "Nan" as output Why & how? I'm using the G compiler
#include <iostream> int main() { float f=0.0f/0.0f; std::cout<<f; return 0; }
Similarly, I have tried similar Java and Java programs C #& it displays "Nan" as output again
class Test { public static void main(String args[]) { float f=0.0f/0.0f; System.out.println(f); } } class Test { public static void Main(string[] args) { float f=0.0f/0.0f; Console.Write(f); } }
I want to know how to implement floating point operation & how it is different from integer operation Is it uncertain behavior in the case of C? If so, why? Please help me
Solution
Nan is not a number Dividing by the integer 0 is always a mistake, because in mathematics you can't divide by 0 Therefore, many languages throw exceptions when divided by the integer 0
Using floating point numbers for this operation is not reasonable because floating point calculations are not accurate For example, the calculation may result in 0.0F because 0.0F is the closest floating-point value of the answer, not because the true value of the answer is mathematically 0.0 Therefore, trying to divide the floating point value by 0.0F may not be the result of an incorrect algorithm Nan essentially means that the answer to the calculation cannot be determined, because it involves the division of two numbers, so the computer cannot distinguish them from 0