I have this equation:
val2 = ((((((((((Math.Pow(((previous_val) + (val5*100)), 1.001)) / 24) / 60) / 60) * 100) / 3600)*h)/m)*s));
previous_val and val5 are local variables that equal other values. The variables h, m, and s represent hours, minutes, and seconds.
My problem: When both, m and s, are equivalent to 0, I get a NaN Instead of my answer.
NaN was also achieved when h and m were equivalent to 0.
What should I add into my code that will throw an exception? I’m sure that the reason for this ‘not a number’ “error” is that I am dividing by zero.
A NaN is easy to produce:
How do/can the zeros in
h,m, andscause that? Remember, once aNaNhas been introduced, it will silently propagate through in most cases. (As others have suggested, breaking the problem up into smaller bite-size portions will aide in debugging — and likely future maintainability 😉While a final (or intermediate)
IsNaNcheck will work to detect the scenario, consider checking/reacting to illegal inputs as well. (I am not sure if there is a way to get [the rare] signaling NaN in C#, which is different than the quiet NaN observed, but quick google searches say: not possible.)Happy coding.
Although [standard] floating point operations will not throw an exception (as
NaNis encoded as a floating point value), integer math operations may throw an exception (asNaNis not encoded). If the operations are such that integer math is sufficient then it can be used to “throw” an exception: