Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ nan help

  1. Feb 28, 2010 #1
    hi there,

    i have written a small program in C++ and if the user puts in the wrong values for some of the variables the operation will end up trying to square root a negative number and this returns that the answer is not a number

    can anyone show me how to write an if function that if
    Code (Text):
    double answerplus
    Code (Text):
    double answerminus
    are not numbers it will display an error message

  2. jcsd
  3. Feb 28, 2010 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I think you're looking for isnan. But it's been a while since I looked at that part of the C library.
  4. Feb 28, 2010 #3
    c++ is a strongly typed language, so if you input a double, it is only going to assign a floating point value to the input variable.

    According to the C++ reference library:

    If the argument is negative, a domain error occurs, setting the global variable errno to the value EDOM.


    So you check that value after processing each square root in your function to ensure that the sqrt() function returned a number, either that or you could check the value before invoking the sqrt() function.
    Last edited by a moderator: Apr 24, 2017
  5. Feb 28, 2010 #4


    User Avatar
    Science Advisor
    Homework Helper

    Or you could call sqrt() in a try : catch{} block - sqrt will throw an exception with a negative number
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook