Search code examples
cprintfsign

How to print sign of a number in C?


While printing a number, I am trying to print its sign before the number. Is there a way to do it without the actually if...else case mentioned in the comment section of the code below.

I have tried getting the sign of the number. But I don't know how to print just the sign.

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

void main(){
    double complex s = 3.14 + 5.14*I;
    printf("\ns is: %f + %f i", creal(s), cimag(s));
    double complex S = conj(s);
    printf("\nConjugate of s is: %f + %f i", creal(S), cimag(S));
}

/*
printf("\nConjugate of s is: %f ", creal(S))
if cimag(S) > 0
    printf("+ %f i", cimag(S))
else
    printf("- %f i", abs(cimag(S)))
*/

If S = 3.14 - 5.14*I, without the if...else condition, I'm expecting to get an output something like this:

3.14 - 5.14 i

Solution

  • First get the sign character:

    double x = ...;
    char c = signbit(x) ? '-' : '+';
    

    Then use it however you want:

    printf ("%c %f", c, fabs(x));