C语言乘方运算

Python018

C语言乘方运算,第1张

C语言的乘方运算可以利用库函数pow。

pow函数原型:double pow( double x, double y )

头文件:math.h/cmath(C++中)

功能:计算x的y次幂。

参考代码:

#include <stdio.h>

#include <math.h>

int main()

{

int a=3,b=2

double t = pow(a,b)//计算3的平方并输出 

printf("%.0lf\n",t)

return 0 

}

/*

输出:

9

*/

C语言中没有乘方运算符,但有计算乘方的函数:pow

函数原型如下:

#include <math.h>   //引用头文件

double pow(double x, double y)    //函数定义方法

表示求x的y次方。

例:求3.2的5次方可写成 pow(3.2 , 5)

当然,你也可以自定义函数求乘方,例:

float power( float x,int n )   //自定义乘方函数

{  int i

   float s=1.0   //初始化变量s,用于存储最终结果值

   for( i=1i<=ni++ )    //利用循环进行计算,n次方就是把x乘上n遍

   s*=x

   return s     //返回最终结果值

}

main()

{ // 定义变量n和x

  int n

  float x

  // 准备输入数据,用来求x的n次方

  printf("请输入x和n(输入时用空格或回车分隔): \n")

  scanf("%f%d",&x,&n)

  // 调用自定义power函数,输出最终结果

  printf("\n%f的%d次方是:%f\n",x,n,power(x,n))

}

在C语言中,乘方也是一种运算

C语言在库函数中提供了一个计算乘方的函数

函数名为pow

函数头文件为 math.h

函数的原型为double pow (double x,double y)

函数的功能为计算 x^y的值,并返回结果