+ 1

Why does my output says 'nan'?

I typed an output to find the determinent of a quadratic equation But the problem is that whenever I run the program and input the numbers the output says 'nan' This is the program: #include<iostream> #include<cmath> using namespace std; int main() { float a,b,c,d,e; cout<<"enter 3 numbers"; cin>>a>>b>>c; d=b*b-4*a*c; e=d; cout<<sqrt(e); }

12th Aug 2017, 3:15 PM
Black Thunder
Black Thunder - avatar
4 Answers
+ 7
nan stands for not a number. If the value of d is negative, then the output will be square root of negative number which is imaginary. In that case it'll print "nan"
12th Aug 2017, 3:23 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 1
use complex.h (might be called ccomplex for C++ but I am not sure), they provide complex operations and numbers
12th Aug 2017, 4:15 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
You can use a simple if statement to check if e is less than zero (OR greater than or equal to zero). Then output something else or perform some other code if e is negative. A few examples: if(e < 0) { cout << "Number is negative. Please try again." << endl; } else { cout<<sqrt(e); } if(e < 0) { e = e * -1; // make e positive } cout<<sqrt(e); if(e > 0) { cout<<sqrt(e); } else { // do something here } // or here
12th Aug 2017, 4:28 PM
ChaoticDawg
ChaoticDawg - avatar
0
So how to get an output even if it is negative Any help would be much appreciated
12th Aug 2017, 3:27 PM
Black Thunder
Black Thunder - avatar