从浮点数中提取个别数字 [英] Extracting individual digits from a float

查看:217
本文介绍了从浮点数中提取个别数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一整天都在这个问题上磕头。我目前正在使用的C ++项目需要显示可编辑的值。当前选定的数字显示上述递增的数值和递减的数值。能够将可编辑的值作为数字和数字集合引用是有用的。如果有一些浮点数的可索引形式,那真是太棒了,但我一直无法找到这样的解决方案。我抛出这个问题,看看是否有什么明显的我失踪或如果我应该滚我自己的。






感谢您的建议!我希望有一个解决方案不能从float - > string - > int转换,但我认为这是摆脱浮点量化问题的最好方法。我结束了与升压::格式,只是参考字符串的个别字符。我不能看到这是一个巨大的性能差异相比,使用modf和fmod的组合来尝试从浮点数(这可能只是在幕后,只有比我的实现更强大的)。

解决方案

浮点数的内部表示并不像你看到的那样。

要进行强制转换,请执行以下操作:

  char string [99]; 
sprintf(字符串,%f,floatValue);

或者看看这个: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1



维基百科的文章可以解释更多关于表达的内容: http://en.wikipedia.org/wiki/Floating_point


I have been banging my head on this one all day. The C++ project I am currently working on has a requirement to display an editable value. The currently selected digit displays the incremented value above and decremented value below for said digit. It is useful to be able to reference the editable value as both a number and collection of digits. What would be awesome is if there was some indexable form of a floating point number, but I have been unable to find such a solution. I am throwing this question out there to see if there is something obvious I am missing or if I should just roll my own.


Thanks for the advice! I was hoping for a solution that wouldn't convert from float -> string -> int, but I think that is the best way to get away from floating point quantization issues. I ended up going with boost::format and just referencing the individual characters of the string. I can't see that being a huge performance difference compared to using combinations of modf and fmod to attempt to get a digit out of a float (It probably does just that behind the scenes, only more robustly than my implementation).

解决方案

Internal representation of the float point numbers aren't like was you see. You can only cast to a stirng.

To cast, do this:

char string[99];
sprintf(string,"%f",floatValue);

Or see this : http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1

The wikipedia article can explain more on the representation: http://en.wikipedia.org/wiki/Floating_point

这篇关于从浮点数中提取个别数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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