C語言測試n的階乘和x的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)鏈接
相關(guān)文章
理解C++編程中的std::function函數(shù)封裝
這篇文章主要介紹了理解C++編程中的std::function函數(shù)封裝,std::function是C++11標(biāo)準(zhǔn)中的新特性,需要的朋友可以參考下2016-04-04
C語言安全編碼之?dāng)?shù)值中的sizeof操作符
這篇文章主要介紹了C語言安全編碼的數(shù)值中的sizeof操作符用法注意事項,需要的朋友可以參考下2014-07-07
淺談關(guān)于指針作為參數(shù)并改變它的值的問題
這篇文章介紹了關(guān)于指針作為參數(shù)并改變它的值的問題,有需要的朋友可以參考一下2013-10-10

