C/C++ Fixing a C++ Program Error: Negative Square Root

Click For Summary
To handle cases where a user inputs invalid values leading to the square root of a negative number in a C++ program, it is essential to implement error checking. The discussion highlights the use of the isnan function to determine if the result of a square root operation is not a number. Additionally, it suggests checking the input value before calling the sqrt() function to prevent domain errors. If a negative number is passed, the global variable errno will be set to EDOM, indicating a domain error. Alternatively, wrapping the sqrt() call in a try-catch block can catch exceptions thrown by the function when a negative number is encountered. This approach ensures that the program can display an appropriate error message to the user.
metalmaniac
Messages
4
Reaction score
0
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
 
Technology news on Phys.org
I think you're looking for isnan. But it's been a while since I looked at that part of the C library.
 
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:
Or you could call sqrt() in a try : catch{} block - sqrt will throw an exception with a negative number
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 30 ·
2
Replies
30
Views
6K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
12
Views
2K
Replies
14
Views
3K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 39 ·
2
Replies
39
Views
5K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 23 ·
Replies
23
Views
3K