我正在尝试用递归函数计算x的指数函数,指数函数是根据这个方程计算的。
我将指数函数分为两部分,第一部分是断裂
(我用底部的递归函数计算了它,然后将这部分放在主函数的 while 循环中,以找到从 0 到 N 的总和
因为我是 c 的初学者,我的英语并不完美,请以简单的方式解释我的错误。
提前感谢.....
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>
double faktoriyel(double x,double N);
int main(){
double N, x, a;
double s = 0;
scanf("%lf", &x);
scanf("%lf", &N);
a = N;
do
{
s += faktoriyel(x, N);
--a;
}while (a > 0);
printf("n%lfn", s);
}
double faktoriyel(double x, double N)
{
if (N < 0)
return -1;
else if (N < 2)
return pow(x, N) / 1;
else
return (pow(x, N) / N * faktoriyel(x, N - 1));
}
你的基本情况不对。它应该是
if(N == 0)
return 1;
为什么,因为任何提高到 0 次方的东西都是 1。所以返回 0。
您的方法不是使用递归的正确方法。检查此代码。
#include <stdio.h>
int power(int n1, int n2);
int main()
{
int base, powerRaised, result;
`printf("Enter base number: ");`
`scanf("%d",&base);`
`printf("Enter power number(positive integer): ");`
`scanf("%d",&powerRaised);`
`result = power(base, powerRaised);`
`printf("%d^%d = %d", base, powerRaised, result);`
`return 0;`
}
int power(int base, int powerRaised)
{
if (powerRaised != 0)
`return (base*power(base, powerRaised-1));`
`else`
`return 1;`
}
我在这里稍微改变了一下:
double faktoriyel(double x,double N)
{
if (N == 0) return 1;
else return (x/N * faktoriyel(x,N-1));
}
为什么?因为你写了
return (pow(x, N) / N * faktoriyel(x, N - 1));
这导致计算(x^(N+(N-1(+.....+1((/(N!(而不是 x^N/N!。
那是因为每次调用函数时都会重新计算 x^N然后乘以它:
(x^N((x^(N-1((....*1
在这里:
do
{
s+=faktoriyel(x,N);
--N;
}while (N>=0);
取而代之的是:
do
{
s += faktoriyel(x, N);
--a;
}while (a > 0);
因为你实际计算了
x^N/N! + x^N/N! +.....+x^N/N!
而不是:
x^N/N! + x^(N-1(/(N-1(! +.....+1;
递减"a"不会递减 N,从而产生在 e^x 的错误计算中。
顺便说一句,它应该可以工作。