c - 如何在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
解决方案
您可以只使用 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 我
推荐阅读
- ruby-on-rails - 在 ruby on rails 中更新
- c++ - 如何用四元数来描述超过 360 度的旋转角度?
- spring-boot - Springboot抛出给杰克逊异常
- azure-functions - 发生错误发送事件:Azure 函数输出适配器未能将事件写入 Azure 函数作为流分析作业输出
- python - 用于获取数千条记录并将其附加到 falsk rest api 列表的高效 pymongo 查询
- ansible - 使用 ansible 在远程位置备份文件
- c# - 创建剪贴板数据以在 Access-Vbe 中使用
- hibernate - 如何在休眠中使用条件查询获取详细信息
- django - 使用 simplejwt 模块在 django 中修改 jwt 访问令牌到期时间
- php - 在 Woocommerce 3+ 中自定义一些结帐字段属性