[英]c program to calculate value of e^x, correct upto 10 decimal places
I am writing a program that calculates the value of e^x, according to the expansion formula.I need to print the answer so that it is correct upto 10 decimal places.我正在编写一个程序,根据展开公式计算 e^x 的值。我需要打印答案,使其正确到小数点后 10 位。 I have tried to do it using, for, while and do while loop, however I cannot figure out where to terminate the loop, which condition to use to terminate the loop.
我尝试使用 for、while 和 do while 循环来执行此操作,但是我无法弄清楚在哪里终止循环,以及使用哪个条件来终止循环。 i have written the code as follows:
我编写的代码如下:
#include<stdio.h>
#include<math.h>
int factorial(int x);
int main()
{
int x,n;
float sum,d_1;
printf("Enter the value of power :");
scanf("%d",&x);
n=1;sum=1;
while(sum <= %.10f)
{
d_1=pow(x,n)/factorial(n);
sum=sum+d_1;
n++;
}
printf("Answer is %f",sum);
return 0;
}
int factorial(int y)
{
int fact=1,i;
for(i=1;i<=y;i++)
{
fact=fact*i;
}
return(fact);
}
and i am getting the error message expected expression before %.我在 %. Please help.
请帮忙。
You want to terminate the loop when the current term is smaller than some value.当当前项小于某个值时,您希望终止循环。 Also you want the loop to execute at least once, so a do-while loop is preferable:
您还希望循环至少执行一次,因此最好使用 do-while 循环:
n = -1;
do {
n++;
d_1 = pow(x, n) / factorial(n);
sum = sum + d_1;
} while (d_1 > epsilon);
As mentioned in the comments, there are other issues with the code when it comes to precision and overflow but that is a different story.正如评论中提到的,代码在精度和溢出方面还有其他问题,但这是另一回事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.