- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在使用的嵌入式 C 没有 round() 函数它是数学库,在 C 中实现它的简洁方法是什么?我正在考虑将它打印成一个字符串,寻找小数位,然后找到句点后的第一个字符,如果 >= 5 则向上舍入,否则向下舍入。等。想知道是否有更聪明的东西。
谢谢,弗雷德
最佳答案
正如许多其他答案所暗示的那样,您可以重新发明轮子。或者,您可以使用其他人的轮子——我建议使用 Newlib 的,它是 BSD 许可的,旨在用于嵌入式系统。它可以正确处理负数、NaN、无穷大和不能表示为整数的情况(由于太大),并以一种使用指数和掩码而不是通常成本更高的浮点运算的有效方式来处理。此外,它会定期进行测试,因此您知道它没有明显的极端情况错误。
Newlib 源代码导航起来可能有点笨拙,所以这里是您想要的部分:
如果你需要那里的其他文件,父目录是这个: https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=tree;f=newlib/libm/common;hb=master
作为记录,这里是 float 版本的代码。如您所见,正确处理所有可能的情况需要一些复杂性。
float roundf(x)
{
int signbit;
__uint32_t w;
/* Most significant word, least significant word. */
int exponent_less_127;
GET_FLOAT_WORD(w, x);
/* Extract sign bit. */
signbit = w & 0x80000000;
/* Extract exponent field. */
exponent_less_127 = (int)((w & 0x7f800000) >> 23) - 127;
if (exponent_less_127 < 23)
{
if (exponent_less_127 < 0)
{
w &= 0x80000000;
if (exponent_less_127 == -1)
/* Result is +1.0 or -1.0. */
w |= ((__uint32_t)127 << 23);
}
else
{
unsigned int exponent_mask = 0x007fffff >> exponent_less_127;
if ((w & exponent_mask) == 0)
/* x has an integral value. */
return x;
w += 0x00400000 >> exponent_less_127;
w &= ~exponent_mask;
}
}
else
{
if (exponent_less_127 == 128)
/* x is NaN or infinite. */
return x + x;
else
return x;
}
SET_FLOAT_WORD(x, w);
return x;
}
关于在 C 中实现 round() 的简洁方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4572556/
我正在用 C# 编写动态语言的解释器,并将原始函数实现为具有虚拟 Apply 方法的抽象类 Primitive,其中每个实际原始函数都是重写 Apply 的子类。 (另一种方法是只拥有类 Primit
我正在用 C# 编写动态语言的解释器,并将原始函数实现为具有虚拟 Apply 方法的抽象类 Primitive,其中每个实际原始函数都是重写 Apply 的子类。 (另一种方法是只拥有类 Primit
我是 Dapper 的新手我正在尝试了解它实际上是如何映射事物的。我有以下数据库结构: calendar | Id | Name | meeting_room | Id | Calendar_id
抱歉问题标题很糟糕。有没有办法在一行中做到这一点: Button button = (Button)Gridview.Cells[0].FindControl("controlname"); butt
在 Java 中在声明点和使用点声明列表/数组文字的tersest方法是什么? 作为次要问题,我更喜欢一种不会导致编译时警告或要求抑制警告的方法。 注意:就我个人而言,这是针对Java 8ish on
什么是现代、简洁、快速的方法来测试节点是否有任何与给定选择器匹配的子节点? “简洁”是指类似于 jQuery 或函数式风格,例如避免循环。我知道本地选择器越来越多地使用这种类型的东西,但没有跟上发展的
getFirstNotNullResult 执行函数列表,直到其中一个函数返回非空值。 如何更优雅/简洁地实现 getNotNullFirstResult? object A { def main
根据 stackoverflow 上某人的推荐,我使用了 jquery succint https://github.com/micjamking/Succinct截断我在 php 网站上的帖子。 它
我是一名优秀的程序员,十分优秀!