Question

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 *

Was it helpful?

Solution

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);
    }
}

OTHER TIPS

Testing for NaN in C++ is tricky. Just use an if statement to avoid evaluating the sqrt if its argument is negative.

A nan number isn't equal to anything, even to itself.
You could simple test to see if if( y != y ).

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;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top