问题描述
今天,我在C,C ++和Java出现了一次采访,问题是我自己写的char * ftoa(浮点NUM)。
Today I appeared for an interview, and the question was writing my own "char * ftoa(float num) " in C, C++ and Java.
是的,我知道浮点数遵循IEEE标准,同时分配他们的记忆,但我不通过使用C中的尾数和指数知道浮到焦炭转化。
Yes, I know float numbers follow IEEE standard while allocating their memory, but I don't know float to char conversion by using Mantissa and Exponent in C.
我没有任何想法,以解决C ++中的上述问题和JAVA。
I don't have any idea to solve the above problem in C++ and JAVA.
的I / P到ftoa():1.23
I/P to the ftoa(): 1.23
O / P从ftoa():1.23(char格式)
O/P from the ftoa(): 1.23 (char format).
在此先感谢...
推荐答案
当你处理FP号码,就可以得到非常COMPEX但算法过于简单和类似埃德加holleis的答案;荣誉!其复杂的,因为当你处理浮点数计算将根据您所选择的precision有点过。这就是为什么它不是良好的编程习惯浮点比较为零。
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';
这篇关于如何实现"字符* ftoa(浮点NUM)"无C,C ++和Java的sprintf()库函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!