sqrt() nan problem

Hi all
I am practicing with user defined functions and in this case I had to write my own sqrt function

I know that somehow I should take into account that user may input a negative number...but I dont know if I am supposed to tell the program to cout "nan"

Is "nan" compiler dependant or is it built in into the sqrt() function.

Last edited on
Add this after the first if-statement block

1
2
3
4
else if(n <= 0) 
{
  cout << "Error: Number less than or equal to zero encountered\n"; // You could make it type NaN here
}


You might want to change the while condition check to n <= 0 so it force the user to reenter a valid number.

}while(n <= 0);


Sometimes the program will print out NaN but I can't produce a situation right now.
Last edited on
Hi and thank you for the reply...
I believe that if I set the condition to n <= 0 then the program would not work right because the sqrt() needs the number to be positive
that is my point...if the user input a negative number, the program should output "nan". This output depends from the compiler?
Last edited on
Okay I just looked it up.

Run the program normally without any checks.

A negative number inputted will result in NaN being printed automatically.

Edit: Oops my mistake. Something else comes up.

It might be compiler dependent.

I would suggest explicitly having the program output NaN if the user enters a negative number.
Last edited on
That's what I was trying to understand...if it was compiler dependent or not...
I cout the "nan" manually and it worked fine
thanks for your help
Last edited on
Topic archived. No new replies allowed.