简体   繁体   中英

c++ negative square root

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 *

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

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(ab) = 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM