How to Print Out the Square Root of A Negative Num

2019-09-24 09:26发布

I am trying to figure out how to display the square root of a number if it happens to be negative (as it is entered by the user), and if so, display it correctly with the "i" displayed as well. When I do the normal sqrt function, the result is always something like -1.#IND. When I tried using the double complex variables, the positive numbers nor the negative numbers would come out clean.

Below is my code; the comments are what my goal is. The 4 num variables are entered by the user and can be any integer, positive or negative.

 //  Display the square root of each number.  Remember that the user can enter negative numbers and 
//  will need to find the negative root with the "i" displayed.
printf("\nThe square root of %d is %.4f", num1, sqrt(num1));
printf("\nThe square root of %d is %.4f", num2, sqrt(num2));
printf("\nThe square root of %d is %.4f", num3, sqrt(num3));
printf("\nThe square root of %d is %.4f", num4, sqrt(num4));

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-24 09:55

Pseudocode:

string root(int num) {
    return "" + sqrt(abs(num)) + (num < 0) ? "i":"";
}

Alternatively:

printf("\nThe square root of %d is %.4f%s", num1, sqrt(abs(num1)), (num1 < 0) ? "i":"");
查看更多
看我几分像从前
3楼-- · 2019-09-24 10:05

You can use:

if ( num1 < 0 )
{
   printf("\nThe square root of %d is %.4fi", num1, sqrt(-num1));
}
else
{
   printf("\nThe square root of %d is %.4f", num1, sqrt(num1));
}
查看更多
趁早两清
4楼-- · 2019-09-24 10:07

If you're working with floating point you can use the built-in complex utilities, e.g.:

#include <complex.h>
#include <stdio.h>

int main(void)
{
    double complex num = -4.0;
    double complex s = csqrt(num);

    printf("%.2f + %.2fi\n", creal(s), cimag(s));
}
查看更多
登录 后发表回答