c++中的数学

本文详细介绍了C++标准库cmath中的数学函数,如sqrt()、fabs()、pow()、ceil()、floor()、round()以及sin(),cos(),tan(),强调了它们的使用方法和注意事项,包括参数类型和弧度单位的转换。

#include <cmath> 是C++标准库中的数学头文件,提供了许多与数学相关的函数,例如三角函数、指数、对数、幂和常用数学常量等。这个头文件不需要额外安装,可以直接在代码中使用。

1.sqrt

sqrt(n) 是数学库cmath.h中的一个函数,用于求一个数的平方根。在C++中调用 sqrt(n) 的方式是,包含头文件 #include <cmath>,然后直接使用函数名调用 sqrt(n),其中 n 是一个数字。例如:

#include <iostream>
#include <cmath>

int main()
{
   double n = 16.0;
   double square_root = sqrt(n);
   std::cout << "The square root of " << n << " is " << square_root << std::endl;
   return 0;
}

那输出将会是

The square root of 16 is 4

2.fabs(x)

fabs(x) 是 C++ 标准库 <cmath> 中的一个函数,用于计算给定数字 x 的绝对值(即其正值)。该函数可以接受整数、浮点数或双精度浮点数作为参数,并返回其绝对值。

使用 fabs(x) 的方法是包含头文件 #include <cmath>,然后直接使用函数名调用 fabs(x),其中 x 是一个数字。例如:

#include <iostream>
#include <cmath>

int main()
{
   int n = -5;
   float f = -3.14;
   double d = -10.5;

   int absolute_n = fabs(n);
   float absolute_f = fabs(f);
   double absolute_d = fabs(d);

   std::cout << "The absolute value of " << n << " is " << absolute_n << std::endl;
   std::cout << "The absolute value of " << f << " is " << absolute_f << std::endl;
   std::cout << "The absolute value of " << d << " is " << absolute_d << std::endl;

   return 0;
}

那输出将会是

The absolute value of -5 is 5
The absolute value of -3.14 is 3.14
The absolute value of -10.5 is 10.5

需要注意的是,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值