math.h庫里有這個(gè)函數(shù),pow(x,n),也可以自己用循環(huán)來寫

創(chuàng)新互聯(lián)建站專注于企業(yè)營銷型網(wǎng)站、網(wǎng)站重做改版、尉氏網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、H5高端網(wǎng)站建設(shè)、成都做商城網(wǎng)站、集團(tuán)公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站建設(shè)公司、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為尉氏等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。
long
fun(int
x,int
n)
{
long
p=1;
int
i;
for
(i=1;i=n;i++)
p*=x;
return
p;
}
在主函數(shù)main()中,直接調(diào)用fun函數(shù)即可
#includestdio.h
#includestring.h
float?insertX(void)
{
float?x;
printf("%s\n",?"請(qǐng)輸入底數(shù)?x:");
scanf("%f",?x);
return?x;
}
int?insertN(void)
{
int?n;
printf("%s\n",?"請(qǐng)輸入指數(shù)?n:");
scanf("%d",?n);
return?n;
}
float?mypow(float?x,?int?n)
{
float?c?=?1.0;
int?i;
for(i=0;?in;?i++)
{
c?*=?x;
}
return?c;
}
void?print(float?c)
{
printf("冪為:\n%.8f\n",?c);
}
int?main(void)
{
float?x?=?insertX();
int?n?=?insertN();
float?c?=?mypow(x,?n);
print(c);
system("pause");
return?0;
}
double pow(double x, double y);
pow()用來計(jì)算以x 為底的 y 次方值,然后將結(jié)果返回
可能導(dǎo)致錯(cuò)誤的情況:
如果底數(shù) x 為負(fù)數(shù)并且指數(shù) y 不是整數(shù),將會(huì)導(dǎo)致 domain error 錯(cuò)誤。
如果底數(shù) x 和指數(shù) y 都是 0,可能會(huì)導(dǎo)致 domain error 錯(cuò)誤,也可能沒有;這跟庫的實(shí)現(xiàn)有關(guān)。
如果底數(shù) x 是 0,指數(shù) y 是負(fù)數(shù),可能會(huì)導(dǎo)致 domain error 或 pole error 錯(cuò)誤,也可能沒有;這跟庫的實(shí)現(xiàn)有關(guān)。
如果返回值 ret 太大或者太小,將會(huì)導(dǎo)致 range error 錯(cuò)誤。
錯(cuò)誤代碼:
如果發(fā)生 domain error 錯(cuò)誤,那么全局變量 errno 將被設(shè)置為 ?EDOM;
如果發(fā)生 pole error 或 range error 錯(cuò)誤,那么全局變量 errno 將被設(shè)置為 ERANGE。
注意,使用 GCC 編譯時(shí)請(qǐng)加入-lm。
#includestdio.h
#includemath.h
intmain()
{ printf("7 ^ 3 = %f\n",pow(7.0,3.0));
printf("4.73 ^ 12 = %f\n",pow(4.73,12.0));
printf("32.01 ^ 1.54 = %f\n",pow(32.01,1.54));
return0;}
輸出結(jié)果:
7 ^ 3 = 343.000000
4.73 ^ 12 = 125410439.217423
32.01 ^ 1.54 = 208.036691
#includestdio.h
int?power(int?x,int?n)
{
if(n==0)
return?1;
elseif(n%2==1)
return?x*power(x,n-1);
else{
int?y=power(x,n/2);
return?y*y;
}
}
int?main()
{
int?a,b,c;
printf("enter x and n:");
setvbuf(stdout,NULL,_IONBF,0);
scanf("%d%d",a,b);
c=power(a,b);
printf("結(jié)果為%d",c);
return?0;
}
擴(kuò)展資料
#includestdio.h
double power(double x,int n);
main()
{
double x;
int n;
printf("Input x,n:");
scanf("%lf,%d",x,n);
printf("%.2lf",power(x,n));
}
double power(double x,int n)
{
double a=1.0;
int i;
for(i=1;i=n;i++)
a*=x;
return a;
}
參考資料:百度百科 - 遞歸調(diào)用
當(dāng)前題目:c語言x的n次方函數(shù)程序 c語言x的n次方怎么寫
文章起源:http://chinadenli.net/article28/dohggjp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供、網(wǎng)站營銷、靜態(tài)網(wǎng)站、定制開發(fā)、網(wǎng)站建設(shè)、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)