问题
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