+ 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); }
4 ответов
+ 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"
+ 1
use complex.h (might be called ccomplex for C++ but I am not sure), they provide complex operations and numbers
+ 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
0
So how to get an output even if it is negative
Any help would be much appreciated