gpt4 book ai didi

转换后的字符串未能包含正确的浮点值

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:17 25 4
gpt4 key购买 nike

我在将 float 转换为 char* 时遇到问题。
我写了一个函数,它将 float 的整数部分放入字符串中,然后放入十进制值。我需要它保留两位小数。但有些事情是非常错误的。它要么输出整数值,要么输出小数点后 1 位。有人可以指导我吗?下面是我的尝试

void float_to_str(char *str, float f, char size)
{

char pos; // position in string

char len; // length of decimal part of result

char* curr; // temp holder for next digit

int value, i ; // decimal digit(s) to convert
float temp;
pos = 0; // initialize pos, just to be sure

value = ( int )f; // truncate the floating point number
snprintf( curr, sizeof(curr), "%d", value);

strncmp( str, curr, strlen( curr ) );

// now str array has the digits before the decimal

if (f < 0 ) // handle negative numbers
{
f *= -1;
value *= -1;
}

len = strlen( str );
pos = len; // position the pointer to the end of the integer part
str[pos++] = '.'; // add decimal point to string

f = f -( float ) value + 0.005;
printf( " the value of f = %f\n", f );

for( i = 0; i < size; ++i )
{

temp = f* 10;
value = ( int )temp ;
snprintf( curr, sizeof(curr),"%d", value );
str[ pos++ ] = *curr;
}

str[ pos ] = '/0';
printf(" debug --> the string is %s \n", str ); // prints only 5 instead of 6455.56
}

int main()
{

float test = 555564.5555;
char arr[ 40 ];
memset(arr, 0, 40 );
FloatToStringNew( arr,test, 2 );

printf( " the float to string is %s", arr ); // OUT Put is 5 which is wrong
return 0;
}

最佳答案

整个 float_to_string 可以简化为(按照 BLUEPIXY 的建议):

void float_to_str(char *str, float f, char size)
{
sprintf(str, "%.*f", size, f);
}

但是,如果您对代码中的错误感兴趣,它就在 for 循环中:

    for( i = 0; i < size; ++i )
{

temp = f* 10; // Value of f stays the same in every iteration
value = ( int )temp ;
snprintf( curr, sizeof(curr),"%d", value );
str[ pos++ ] = *curr;
}

修复:

    for( i = 0; i < size; ++i )
{

f = f * 10; // Modify f each iteration
value = ( int )f;
snprintf( curr, sizeof(curr),"%d", value );
str[ pos++ ] = *curr;
f = f - (int)f; // Remove the integer part
}

编辑:

函数中还有一些其他的东西需要修复:

strncmp 应该是 strcpy

pos 应该是 intsize_t

类型

curr 应该是数组而不是指针。

main 的调用应该是 float_to_string,而不是 FloatToStringNew

当我编译时出现警告时,编译器帮助我找到了它们(我在 gcc 中使用了 -Wall)。

关于转换后的字符串未能包含正确的浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30867925/

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