将一个float转换为一个字符串 [英] Convert a float to a string

查看:127
本文介绍了将一个float转换为一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用库函数的情况下将浮点整数转换为C / C ++中的字符串 sprintf



<我正在寻找一个功能,例如 char * ftoa(float num) num 转换为字符串并返回。 b

ftoa(3.1415)应该返回3.1415

解决方案

在处理fp数字时,它可能会非常复杂,但算法简单,与edgar holleis的答案类似。荣誉!它的复杂性是因为当你处理浮点数时,根据你选择的精度,计算会有一些偏差。这就是为什么它不是一个好的编程习惯来比较一个浮点数为零。

但是有一个答案,这是我的实现它的尝试。在这里,我使用了一个公差值,所以你不会计算太多的小数位,导致无限循环。我确信有可能有更好的解决方案,但这应该会帮助你很好地理解如何去做。

  char fstr [80]; 
float num = 2.55f;
int m = log10(num);
int数字;
浮动容差= .0001f;

while(num> 0+ precision)
{
float weight = pow(10.0f,m);
digit = floor(num / weight);
num - =(digit * weight);
*(fstr ++)='0'+ digit;
if(m == 0)
*(fstr ++)='。';
m--;
}
*(fstr)='\0';


How can I convert a floating point integer to a string in C/C++ without the library function sprintf?

I'm looking for a function, e.g. char *ftoa(float num) that converts num to a string and returns it.

ftoa(3.1415) should return "3.1415".

解决方案

When you're dealing with fp numbers, it can get very compex but the algorithm is simplistic and similar to edgar holleis's answer; kudos! Its complex because when you're dealing with floating point numbers, the calculations will be a little off depending on the precision you've chosen. That's why its not good programming practice to compare a float to a zero.

But there is an answer and this is my attempt at implementing it. Here I've used a tolerance value so you don't end up calculating too many decimal places resulting in an infinite loop. I'm sure there might be better solutions out there but this should help give you a good understanding of how to do it.

char fstr[80];
float num = 2.55f;
int m = log10(num);
int digit;
float tolerance = .0001f;

while (num > 0 + precision)
{
    float weight = pow(10.0f, m);
    digit = floor(num / weight);
    num -= (digit*weight);
    *(fstr++)= '0' + digit;
    if (m == 0)
        *(fstr++) = '.';
    m--;
}
*(fstr) = '\0';

这篇关于将一个float转换为一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆