spyC
spyC

Reputation: 45

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

Upvotes: 1

Views: 8593

Answers (3)

spyC
spyC

Reputation: 45

With the help of answers from @Antoine and @yhyrcanus, the simplest way to code for space is:

double complex s = 3.14 - 5.14*I;        
printf("\ns is: %f %c %f i", creal(s), signbit(cimag(s)) ? '-' : '+',cabs(cimag(s)));

Upvotes: 1

user1157391
user1157391

Reputation:

First get the sign character:

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

Then use it however you want:

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

Upvotes: 2

yhyrcanus
yhyrcanus

Reputation: 3813

You can just use the printf sign flag. +

#include <stdio.h>

int main()
{

    float f  = 1.0;
    printf("%f%+f",f,f);

    return 0;
}

Output

1.000000+1.000000

Change to -1:

-1.000000-1.000000

If you really need the spaces, you're going to have to do something like you described:

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



void complexToString(double complex num, char * buffer){
    double imag = cimag(num);
    char sign = (imag<0) ? '-':'+';
    sprintf(buffer,"%f %c %f i",creal(num),sign,fabs(imag));
}


int main()
{

    double complex s = 3.14 + 5.14*I;
    char buffer[50];
    complexToString(s,buffer);
    printf("%s",buffer);

    return 0;
}

output:

3.140000 + 5.142000 i

Upvotes: 6

Related Questions