Convert a float to a string(将浮点数转换为字符串)
问题描述
如何在没有库函数 sprintf
的情况下将浮点整数转换为 C/C++ 中的字符串?
How can I convert a floating point integer to a string in C/C++ without the library function sprintf
?
我正在寻找一个函数,例如char *ftoa(float num)
将 num
转换为字符串并返回.
I'm looking for a function, e.g. char *ftoa(float num)
that converts num
to a string and returns it.
ftoa(3.1415)
应该返回 "3.1415"
.
推荐答案
当你处理 fp 数字时,它会变得非常复杂,但算法很简单,类似于 edgar holleis 的答案;赞!它很复杂,因为当您处理浮点数时,根据您选择的精度,计算会有些偏差.这就是为什么将浮点数与零进行比较不是好的编程习惯.
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) = ' ';
这篇关于将浮点数转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将浮点数转换为字符串
基础教程推荐
- 设计字符串本地化的最佳方法 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01