不怎么重要的前言
上一篇我们介绍了什么是指标,不晓得大家有没有比较了解地址的概念?
接下来我们来介绍Math函式库吧!
函式库?
还记得在遥远的第三篇我们有介绍在写主函式(main function)前,必须先做好一件事就是引入函式库。
一般来说在程式的开头,我们就会先把会用到的函式库(工具包)引入,我们那时候形容函式库像是汇集了很多函式(工具)的工具包,而我们每次写程式都会引入的「#include <stdio.h>」就是很好的例子,因为「stdio.h」函式库包含了我们很常使用到的printf和scanf,往后也会提到别的函式。
至于「stdio.h」函式库具体包含了什么样的函式,我们可以参考下面这个连结:
<stdio.h> - C语言标準库(gitbook)
既然大概有了函式库的概念,我们接下来要提一下也很好用的函式库--「<math.h>」。
Math函式库
<math.h>是一个包含了许多数学常用计算的函式库,这个函式库的函式基本是以double的资料型态运算与返值,诸如常见的次方计算、log运算、平方根、绝对值、三角函数、自然对数运算,这些都可以在<math.h>中找到对应函式来协助处理,其中也有数学中常应用的常数也被定义。
接下来我们来介绍<math.h>包含的内容:
常数(1) 介绍
(2) 实际应用
a. 直接使用
#include <stdio.h>#include <math.h>int main(){ printf("M_PI: %f\n", M_PI); printf("M_E: %f\n", M_E); return 0;}
b. 用变数储存使用
#include <stdio.h>#include <math.h>#define pi M_PIint main(){ double e = M_E; printf("pi: %f\n", pi); printf("e: %f\n", e); return 0;}
(1) 介绍
(2) 实际应用
#include <stdio.h>#include <math.h>#define pi M_PIint main(){ printf("pow: %f\n", pow(2,10)); printf("exp: %f\n", exp(1)); printf("sqrt: %f\n", sqrt(100)); printf("fabs: %f\n", fabs(-1.2345)); printf("ceil: %f\n", ceil(1.2345)); printf("fmod: %f\n", fmod(4.92345,1.2)); printf("log: %f\n", log(1)); printf("log10: %f\n", log10(100)); printf("sin: %f\n", sin(pi/2)); printf("cos: %f\n", cos(0)); return 0;}