现在的位置: 首页 > 综合 > 正文

C语言入门(6)——C语言常用数学函数

2014年10月08日 ⁄ 综合 ⁄ 共 2227字 ⁄ 字号 评论关闭

 

在编码过程中会经遇到数学运算,幸运的是C语言提供了非常丰富的数学函数库。

在数学中使用函数有时候书写可以省略括号,而C语言要求一定要加上括号,例如sin(pi/2)这种形式。在C语言的术语中,pi/2是参数,sin是函数,sin(pi/2)是函数调用。

函数调用也是一种表达式。这个表达式由函数调用运算符(也就是括号)和两个操作数组成,操作数sin称为Function Designator,是函数类型的,操作数pi/2是double型的。这个表达式的值就是sin(pi/2)的计算结果,在C语言的术语中称为函数的返回值。

 

下面演示一些常用的函数用法。在使用数学函数需要时要引入头文件math.h。

 

 

1、函数名:abs

   功能:返回整型数的绝对值.

   用法:Abs(number)

number 参数可以是任意有效的数值表达式。如果 number 包含 Null,则返回 Null;如果是未初始化变量,则返回 0.

代码举例:

#include <stdio.h>
#include <math.h>
int main()
{
    intnumber = -1234;
    printf("数字: %d 的绝对值是: %d \n", number, abs(number));
    system("pause");
    return0;
}

运行结果:

 

 

2、函数名:fabs

   功能:求浮点数x的绝对值.

   用法:fabs(double x);

代码举例:

#include <stdio.h>
#include <math.h>
int main()
{
    floatnumber = -1234.0;
    printf("数字: %f 的绝对值是: %f \n", number, fabs(number));
    system("pause");
    return0;
}

 

运行结果:

 

3、函数名:sqrt

    功能:返回指定数字的平方根.

    用法:sqrt  (double x);

说明:sqrt即平方根计算(Square Root Calculations),通过这种运算可以考验CPU的浮点能力。

代码举例:

#include <math.h>
#include <stdio.h>
int main(void)
{
    doublex = 4.0, result;
    result =sqrt(x);
    printf("%f 的平方根是 %f\n", x, result);
    system("pause");
    return0;
}

运行结果:

 

4、函数名:pow

    功能:返回指定数字的指定次幂.

用法:pow   (double x, double y);(将返回x的y次幂)

返回值:x不能为负数且y为小数,或者x为0且y小于等于0,返回幂指数的结果。

返回类型:double型,int,float会给与警告!

代码举例: 

#include<math.h>
#include<stdio.h>
 
int main(void)
{
    doublex = 2.0, y = 3.0;
    printf("%lf 的 %lf 次方是 %lf\n", x, y, pow(x, y));
    system("pause");
    return0;
}

 

运行结果:

 

5、函数名: frexp

功  能:把一个双精度数分解为尾数的指数

用  法:double frexp(doublevalue, int *eptr);

参数:

x : 要分解的浮点数据

expptr : 存储指数的指针

返回值:返回尾数

说 明:其中 x = 尾数 * 2^指数

 代码举例:

#include <math.h>
#include <stdio.h>
int main(void)
{
    doublemantissa, number;
    intexponent;
    number =8.0;
    mantissa =frexp(number, &exponent);
    printf("数字 %lf 是 %lf 乘以2的 %d 次方\n", number, mantissa, exponent);
    system("pause");
    return0;
}

运行结果:

 

验证:8 = 0.5* 2^4 = 0.5 * 16

  

6、函数名:ceil / floor

功能: 向上舍入/向下舍入

用法:double ceil(doublex);

    double floor(double x);

 

代码举例:

#include<math.h>
#include<stdio.h>
int main(void)
{
    doublenumber = 123.54;
    doubledown, up;
    down =floor(number);
    up =ceil(number);
    printf("数字:%5.2lf\n", number);
    printf("向下舍入的结果:%5.2lf\n", down);
    printf("向上舍入的结果:%5.2lf\n", up);
 
    system("pause");
    return0;
}

运行结果:

 

 

7、函数名: atof  (const char *s);

  功  能: 把字符串转换成浮点数

  用  法: double atof(constchar *nptr);

代码举例:

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
	float arg, *point = &arg;
	float f;
	char *str = "12345.67";
	f = atof(str);
	printf("string = %s float = %f\n", str, f);

	system("pause");
	return 0;
}

运行结果:

 

C语言关于数学运算的函数还有很多,例如三角函数、对数函数等,用法比较简单,就不一一举例了。

抱歉!评论已关闭.