C語言測(cè)試n的階乘和x的n次方
題目描述
輸入一個(gè)正數(shù)x和一個(gè)正整數(shù)n,求下列算式的值。要求定義兩個(gè)調(diào)用函數(shù):fact(n)計(jì)算n的階乘;mypow(x,n)計(jì)算x的n次冪(即xn),兩個(gè)函數(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ù)實(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é)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
C++ 中消息隊(duì)列函數(shù)實(shí)例詳解
這篇文章主要介紹了C++ 中消息隊(duì)列函數(shù)實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-06-06
C語言中邏輯運(yùn)算符與條件運(yùn)算符的學(xué)習(xí)教程
這篇文章主要介紹了C語言中邏輯運(yùn)算符與條件運(yùn)算符的學(xué)習(xí)教程,條件運(yùn)算符問號(hào)即三目運(yùn)算符使用起來十分方便,需要的朋友可以參考下2016-04-04

