area = pow(4.0,2);
该语句包含对 pow 函数的调用。括号内的数字是实参,也就是发送到函数的信息。pow 函数总是以第一个参数为底数,第二个参数为指数。在本示例中,4.0 是底数,2 是指数。结果从该函数返回,并在调用了该函数的语句中使用。area = pow(4.0,2) 与以下代数表达式是等效的:Area = 42
以下是另外一个使用 pow 函数的示例,它将 3X63 的结果赋值给 x:x = 3 * pow(6.0, 3);
以下语句显示了底数为 5、指数为 4 的幂值:cout << pow(5.0, 4);
可以将 pow 函数视为一个“黑箱”,它接收 2 个数字,然后发送出第 3 个数字。发出来的数字是以第一个数字为底数、第二个数字为指数的幂值,如图 2 所示。area = pow(4.0, 2);
下面的程序解决了一个简单的代数问题。它要求用户输入圆的半径,然后计算圆的面积:
// This program calculates the area of a circle. The formula for the area of a circle is PI times the radius squared. PI is 3.14159. #include <iostream>
#include <cmath> // Needed for the pow function
using namespace std;
int main()
{
double area, radius;
cout << "This program calculates the area of a circle. \n";
// Get the radius
cout << "What is the radius of the circle? ";
cin >> radius;
// Compute and display the area
area = 3.14159 * pow(radius, 2);
cout << "The area is " << area << endl;
return 0;
}
程序输出结果为:
This program calculates the area of a circle.
What is the radius of the circle? 10
The area is 314.159
area = 3.14159 * radius * radius;
当然,pow函数在涉及较大指数的运算中是很有用的。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有