How to Print Out the Square Root of A Negative Number with i Displayed in C

别说谁变了你拦得住时间么 提交于 2019-12-14 03:34:45

问题


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

回答1:


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



回答2:


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



回答3:


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":"");


来源:https://stackoverflow.com/questions/35052864/how-to-print-out-the-square-root-of-a-negative-number-with-i-displayed-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!