[英]To print the answer from the series -> x^3 - x^5 + x^7 - x^9 +
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int x,n;
float sum=0;
printf("Length and Value");
scanf("%d%d",&n,&x);
for(int i=1;i<=n;i++)
{
sum+=(pow(x,2*i+1) * pow(-1,i+1));
}
printf("%f",sum);
return 0;
}
I'm trying to solve this series in C language. 我正在尝试用C语言解决这个系列。 Am I doing something wrong in the above code? 我在上面的代码中做错了吗?
Yes, you're a bit wrong. 是的,你有点不对。 In your code 在你的代码中
printf("%f",sum);
sum
is an int
and using %f
to print the value of an int
is undefined behaviour . sum
是一个int
,使用%f
打印一个int
的值是未定义的行为 。
The function pow
() returns a double
. 函数pow
()返回double
。 You may want to change your sum
to type double
. 您可能需要将sum
更改为double
。
If you don't mind using your own version, a better looking implementation, without using pow()
will be 如果您不介意使用自己的版本,则无需使用pow()
即可实现外观更好的实现
x * x
on each iteration 每次迭代乘以x * x
First things first, your printf
has the wrong format specifier for an int
: use %d
instead. 首先,您的printf
的int
格式说明符错误:请改用%d
。 But for non-integral x
, you'll want to refactor to a double
anyway, so %f
will probably be retained. 但是对于非整数x
,无论如何您都希望将其重构为double
,因此%f
可能会保留。
Secondly, don't use pow
: it will not be precise (probably implemented as exp(log)
) and you don't need to evaluate the power from scratch for each term. 其次,不要使用pow
:它不会很精确(可能实现为exp(log)
),并且您不需要为每个术语从头开始评估功效。
Keep a running power: ie compute x * x * x
initially, then successively multiply that by x * x
for subsequent terms. 保持运行能力:即先计算x * x * x
,然后相继乘以x * x
表示后续项。 Don't forget to alternate the signs: you can do that by multiplying by -1. 别忘了交替显示符号:您可以乘以-1。
you are trying to find x^3,x^5 that is power in odd. 您试图找到x ^ 3,x ^ 5奇数次幂。 so do a little change in your for loop. 因此,请在您的for循环中进行一些更改。 write this instead of your code. 写这个代替你的代码。 and if you give a large x or n value then it is preferable to declare sum as a long data type 如果给定较大的x或n值,则最好将sum声明为长数据类型
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int x,n;
long sum=0;
printf("Length and Value");
scanf("%d%d",&n,&x);
for(int i=2;i<=n;i+=2)
{
sum+=(pow(x,i+1) * pow(-1,i));
}
printf("%l",sum);
return 0;
}
First of all, you are trying to evaluate a series that diverges for all points outside and on the circle of radius one (as a complex series). 首先,您正在尝试评估一个在半径为1的圆上和之外的所有点均发散的级数(作为复杂级数)。 If you use an int
for x, you will get each time values bigger and bigger, oscillating around 0. Try it with numbers of ||x|| < 1
如果对x使用int
,则每次的值都将越来越大,在0附近振荡。尝试使用||x|| < 1
数字进行操作。 ||x|| < 1
(this means double
or float
for x) ||x|| < 1
(这意味着x的double
或float
)
All the other answers posted are also usefull to get sooner to the expected value. 发布的所有其他答案也有助于更快地达到预期值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.