C++ nan help

  • C/++/#
  • Thread starter metalmaniac
  • Start date
  • #1

Main Question or Discussion Point

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:
double answerplus
or
Code:
double answerminus
are not numbers it will display an error message


thanks
 

Answers and Replies

  • #2
Hurkyl
Staff Emeritus
Science Advisor
Gold Member
14,916
17
I think you're looking for isnan. But it's been a while since I looked at that part of the C library.
 
  • #3
246
6
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.

http://www.cplusplus.com/reference/clibrary/cmath/sqrt/

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:
  • #4
mgb_phys
Science Advisor
Homework Helper
7,774
12
Or you could call sqrt() in a try : catch{} block - sqrt will throw an exception with a negative number
 

Related Threads for: C++ nan help

  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
17
Views
3K
Replies
2
Views
3K
Replies
1
Views
23K
Replies
3
Views
5K
  • Last Post
Replies
6
Views
745
Top