C語言測試n的階乘和x的n次方
更新時間:2019年02月01日 12:01:01 作者:碼農(nóng)-嵌入式Linux
今天小編就為大家分享一篇關(guān)于C語言測試n的階乘和x的n次方,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
題目描述
輸入一個正數(shù)x和一個正整數(shù)n,求下列算式的值。要求定義兩個調(diào)用函數(shù):fact(n)計算n的階乘;mypow(x,n)計算x的n次冪(即xn),兩個函數(shù)的返回值類型是double。

×輸出保留4位小數(shù)。
輸入
x n
輸出
數(shù)列和
樣例輸入
2.0 3
樣例輸出
1.3333
答案
/*************************************************************************
> File Name: 2.c
> Author:
> Mail:
> Created Time: Wed 12 Dec 2018 09:03:22 AM CST
************************************************************************/
#include<stdio.h>
double fact(int n)
{
double s = 1.0;
for(int i=1; i<= n; i++)
{
s=s*i;
}
return s;
}
double mypow(double x,int n)
{
double s = 1.0;
//printf("%lf %d\n",x,n);
if(n == 0)
{
return 1.0;
}
if(n == 1)
{
return x;
}
s = x;
for(int i =0;i<n-1;i++)
{
s = x*s;
}
//printf("%lf \n",s);
return s;
}
void main(void)
{
double x = 0.0;
int n = 0;
double s;
scanf("%lf %d",&x,&n);
//printf("%lf\n",mypow(-1.0,2));
if(n == 1)
{
s = x;
}
else
{
s = x;
for(int i=2;i<=n;i++)
{
s = s+ mypow(-1.0,i-1)*mypow(x,i)/fact(i);
}
}
printf("%.4lf\n",s);
}
同事提供的答案,不用函數(shù)實現(xiàn)
#include <stdio.h>
int main ()
{
double x, ret, tmp1, tmp2;
int n, i, j;
while (~scanf("%lf %d", &x, &n))
{
ret = 0;
for (i = 1; i <= n; i++)
{
tmp1 = 1;
for (j = 1; j <= i; j++)
{
tmp1 *= x;
}
tmp2 = 1;
for (j = 1; j <= i; j++)
{
tmp2 *= j;
}
if (i % 2 == 1)
{
ret += tmp1 / tmp2;
}
else
{
ret -= tmp1 / tmp2;
}
}
printf("%.04f\n", ret);
}
return 0;
}
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接

