c++中math.pi
时间: 2024-01-22 07:20:56 浏览: 26
C++标准库中并没有定义常量pi,但可以使用数学库中的常量M_PI来表示pi的值。需要包含头文件<cmath>。例如:
```
#include <iostream>
#include <cmath>
int main() {
double r = 5.0;
double area = M_PI * r * r;
std::cout << "The area of the circle is: " << area << std::endl;
return 0;
}
```
输出为:
```
The area of the circle is: 78.5398
```
相关问题
c++ 中 M_PI
M_PI 是一个常量,表示圆周率π的近似值(3.14159265358979323846),在 C++ 的 math.h 或 cmath 头文件中定义。通常用于计算圆的周长和面积,以及球的表面积和体积等数学计算中。以下是一个例子:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double radius = 5.0;
double circumference = 2 * M_PI * radius;
double area = M_PI * pow(radius, 2);
cout << "Radius: " << radius << endl;
cout << "Circumference: " << circumference << endl;
cout << "Area: " << area << endl;
return 0;
}
```
输出结果为:
```
Radius: 5
Circumference: 31.4159
Area: 78.5398
```
用c++的math库
C++ 的 math 库提供了许多数学函数的实现,包括三角函数、指数函数、对数函数、幂函数等等。下面是一些常用的函数和它们的用法:
1. sin(x):求正弦函数的值,x 为弧度制角度。
```c++
#include <cmath>
double x = M_PI / 2.0;
double y = sin(x); // y = 1.0
```
2. cos(x):求余弦函数的值,x 为弧度制角度。
```c++
#include <cmath>
double x = 0.0;
double y = cos(x); // y = 1.0
```
3. tan(x):求正切函数的值,x 为弧度制角度。
```c++
#include <cmath>
double x = M_PI / 4.0;
double y = tan(x); // y = 1.0
```
4. exp(x):求 e 的 x 次幂。
```c++
#include <cmath>
double x = 1.0;
double y = exp(x); // y = 2.71828...
```
5. log(x):求以 e 为底的对数函数值。
```c++
#include <cmath>
double x = 10.0;
double y = log(x); // y = 2.30258...
```
6. pow(x, y):求 x 的 y 次幂。
```c++
#include <cmath>
double x = 2.0;
double y = 3.0;
double z = pow(x, y); // z = 8.0
```
除此之外,math 库还提供了许多其他的数学函数,你可以查看 C++ 标准库中的文档来了解更多的信息。