Fixing a C++ Program Error: Negative Square Root

Click For Summary

Discussion Overview

The discussion revolves around handling errors in a C++ program related to calculating the square root of negative numbers. Participants explore methods to prevent or manage the occurrence of non-numeric results when invalid input is provided by the user.

Discussion Character

  • Technical explanation, Debate/contested, Homework-related

Main Points Raised

  • One participant suggests using the isnan function to check for non-numeric results.
  • Another participant notes that C++ is strongly typed and that a domain error occurs if the input to the sqrt function is negative, which sets errno to EDOM.
  • A different participant proposes checking the value before calling the sqrt function to avoid errors.
  • Another approach mentioned involves using a try-catch block to handle exceptions thrown by the sqrt function when given a negative number.

Areas of Agreement / Disagreement

Participants present multiple competing views on how to handle the error, with no consensus on a single approach being established.

Contextual Notes

There are limitations regarding the handling of errors in C++, including the need to manage global variables like errno and the behavior of exceptions in the context of the sqrt function.

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
 

Similar threads

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