标准库函数abs()
声明在stdlib.h
中,而fabs()
在math.h
中。
为什么它们存在不同的头文件中?
标准库函数abs()
声明在stdlib.h
中,而fabs()
在math.h
中。
为什么它们存在不同的头文件中?
math.h 最初出现在第七版研究 Unix 中。很难说它是怎么来的。例如,[1] 声称 C 库的一些部分是从“PWB/Unix”合并而来的,其中包括 troff
和 C 编译器 pcc
,但我无法证明。
另一个有趣的信息是来自 V7 Unix 的库手册:intro.3:
如果您查看V7命令的makefile,只有少数C程序链接了
(3) These functions, together with those of section 2 and those marked (3S), constitute library libc, which is automatically loaded by the C compiler cc(1) and the Fortran compiler f77(1). The link editor ld(1) searches this library under the `-lc' option. Declarations for some of these functions may be obtained from include files indicated on the appropri- ate pages.
<...>
(3M) These functions constitute the math library, libm. They are automati- cally loaded as needed by the Fortran compiler f77(1). The link editor searches this library under the `-lm' option. Declarations for these functions may be obtained from the include file <math.h>.
-lm
标志。因此我的结论是推测性的:
libm.a
(以及math.h
)主要是为FORTRAN程序而设计的,因此将其分离为库以减少二进制文件的占用空间(请注意,它是静态链接的)。1. UNIX演化史:1975-1984年之前的UNIX历史
2. PDP-11体系结构
大多数运算符,如+ - / *,也是数学运算符,但这些也很容易获得。在编程时,您使用了很多数学知识,开发人员已经开始区分日常所需的数学和更专业的数学,您只需要使用其中一部分。Abs是那些经常使用的函数之一。就像指针算术一样,当您只想知道差异以计算内存块的大小时。但您不感兴趣知道哪个在内存中更高,哪个更低。
因此,总结一下:abs经常被使用,因为它计算两个整数之间的差异。例如,两个指针之间的差异也是一个整数。因此它在stdlib.h中。然而,fabs不是您经常需要的东西,除非您正在进行特定的数学工作。因此它在math.h中。
abs()
适用于int
类型,fabs()
适用于double
类型。 - Weather Vanemath.h
标头;反之,fabs
应归入其他浮点定义。 - Weather Vane