gpt4 book ai didi

c - 去掉C中 float 的无用0

转载 作者:行者123 更新时间:2023-11-30 21:20:03 26 4
gpt4 key购买 nike

如何删除不影响数值的零

 float X1 = (-b + sqrt(pow(b,2) - (4*a*c)))/(2*a);

有时,如果 X1 是一个不带小数的数字,它将是 X1=4.0000我怎样才能避免这种情况

{已编辑}

最佳答案

选项#1

使用printf%g

Unless alternative representation is requested the trailing zeros are removed, also the decimal point character is removed if no fractional part is left.

代码示例:

double x = 4.0;
printf("DEBUG:%f\n", x);
printf("X1=%g\n", x);

输出:

DEBUG:4.000000
X1=4

选项#2

将其输出到字符串并进行处理。

代码示例:

double x = 4.0;
char buff[48];
int len;
len = snprintf(buff, sizeof buff, "%.4f", x);
printf("DEBUG:%s\n", buff);
char *p = buff + len -1;
while(*p == '0'){
*p-- = 0;
}
if(*p == '.')
*p = 0;
printf("X1=%s\n", buff);

输出:

DEBUG:4.0000
X1=4

关于c - 去掉C中 float 的无用0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43831645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com