首页 > 解决方案 > 如何在C中打印数字的符号?

问题描述

在打印数字时,我试图在数字之前打印它的符号。如果没有下面代码的注释部分中提到的实际 if...else 情况,有没有办法做到这一点。

我试过得到号码的符号。但我不知道如何只打印标志。

#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)))
*/

如果 S = 3.14 - 5.14*I,没有 if...else 条件,我希望得到如下输出:

3.14 - 5.14 i

标签: cprintfsign

解决方案


您可以只使用 printf 标志标志。+

#include <stdio.h>

int main()
{

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

    return 0;
}

输出

1.000000+1.000000

更改为 -1:

-1.000000-1.000000

如果你真的需要空间,你将不得不做你描述的事情:

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

输出:

3.140000 + 5.142000 我


推荐阅读