在 C 中将 double 值转换为 char 数组
如何在 C 中将 double 值转换为 char 数组?
double a=2.132;
char arr[8];
在标准C中有什么办法可以做到这一点吗?谁能给出任何解决方案吗?
How do I convert double value to a char array in C?
double a=2.132;
char arr[8];
Is there any way to do this in standard C? Can anyone give any solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您要存储双数据,而不是可读表示,那么:
If you are about to store the double DATA, not the readable representation, then:
要以人类可读的形式表示数字的字符串,请使用 snprintf(),如下面的代码所示。
要访问双精度数的字节,请使用联合。例如,union u { double d;字符数组[8];但是
,从您添加的评论来看,也许您的意思是将数字从字符转换为双精度。请参阅下面代码中的 atof() 调用。该代码产生以下 4 行输出:
代码:
To make a character string representing the number in human-readable form, use snprintf(), like in code below.
To access the bytes of the double, use a union. For example, union u { double d; char arr[8]; }
However, from your added comment, perhaps you mean to convert a number from characters to double. See the atof() call in code below. The code produces the following 4 output lines:
Code:
如果有人看到这个,你也可以尝试 sprintf:
示例:
In case someone looks at this, you can also try sprintf:
Example:
尽管我看到了一些答案,但我想您想查看代码 - 我将只使用 snprintf,尽管您可能更喜欢更安全的形式:
更多信息请参见: http://msdn.microsoft.com/en-us/library/2ts7cx93(VS.71).aspx
Although I see some answers, I imagine you'd like to see code -- I'll just use snprintf although you might prefer a more secure form:
more here: http://msdn.microsoft.com/en-us/library/2ts7cx93(VS.71).aspx
如果您要问的是如何找出内存中的 double 值由哪些字节组成,请尝试以下操作:
尽管您可能想要 unsigned char,而不是 char
If what you are asking is how to find out what bytes make up the double value in memory, try this:
although you probably want unsigned char, not char
双b=222.215;
double b=222.215;