C/C++ 中,平方函数和开方函数都有现成的库函数可以使用,不需要自己重写。

  • 平方函数使用 pow() 函数,代码示例如下:
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int num = 5;
    int squared = pow(num, 2);
    // Squared value of 5 is 25
    cout << "Squared value of " << num << " is " << squared << endl;
   
    return 0;
}

上面的代码中,pow() 函数需要包含 <cmath> 头文件,接收两个参数,第一个是底数,第二个是乘幂的指数,返回值为底数的乘幂值。

  • 开方函数使用 sqrt() 函数,示例代码如下:
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int num = 25;
    double squareRoot = sqrt(num);
    // Square root of 25 is 5
    cout << "Square root of " << num << " is " << squareRoot << endl;
    
    return 0;
}

上面的代码中,sqrt() 函数需要包含 <cmath> 头文件,接收一个参数,为待求开方数值,返回值为该数值的平方根。

【注意】:pow() 函数的返回值为 double 类型,如果需要将其赋值给 int 类型的变量,需要进行强制类型转换。sqrt() 函数的返回值为 double 类型,如果需要将其转换为其他类型,可以使用 C++ 类型转换的语法。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐