问题
My goal is to print ***
if the square root is negative. But I can't think of a way to change default nan
text to ***
for(int i=x1;i<=x2;i++){
double y = sqrt(pow(i,2)+3*i-500);
if(y = ?){
outFile << "***";
}
So, what should I write in the if statement to make it possible? Or maybe there is another way to check if the y is nan then print *
回答1:
How about checking for a negative input to the square root function?
for (int i = x1; i <= x2; ++i)
{
double x = pow(i, 2) + 3*i - 500;
if (x < 0)
{
outFile << "***";
}
else
{
outFile << sqrt(x);
}
}
回答2:
Testing for NaN in C++ is tricky. Just use an if
statement to avoid evaluating the sqrt
if its argument is negative.
回答3:
A nan number isn't equal to anything, even to itself.
You could simple test to see if if( y != y )
.
回答4:
My goal is to print * if the square root is negative. But I can't think of a way to change default nan text to *
A square root never is negative. But it may be complex. See https://en.wikipedia.org/wiki/Complex_number
The idea is to expand the set of numbers into the so called complex plane, which contains a special number i for which is defined i² = -1. This allows us to generalize square roots:
sqrt(a b) = sqrt(a) sqrt(b)
So we can break down sqrt(-a) into sqrt(-1) sqrt(a) = i sqrt(a)
This allows us to change your program into
for(int i=x1;i<=x2;i++){
double X = pow(i,2)+3*i-500;
double y = sqrt(abs(x));
if(X < 0){
outFile << y << "i";
} else {
outFile << y;
}
}
来源:https://stackoverflow.com/questions/9053064/c-negative-square-root