有和没有递归的序列
我有一个序列。
a1 = 1 - cos(x);
ai = a1 + (-1)^(i-1) * x^(2*i-2) / (2*i-2)!
我需要用递归和不用递归来写这个。但它有不同的结果。
这是我的代码: http://codepaste.net/q213q6
I have a sequence.
a1 = 1 - cos(x);
ai = a1 + (-1)^(i-1) * x^(2*i-2) / (2*i-2)!
I need to write this with and without recursion. But it has a different results.
Here is my code: http://codepaste.net/q213q6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将假设这是作业,如果我错了,我会回来编辑这篇文章或重新发布。
首先,您应该尝试以尾递归方式编写阶乘函数。虽然它在 C 中可能不会有太大区别,但这是一个很好的实践。
接下来,您通常不想在递归函数中放置循环,这在某种程度上违背了这一点。将递归调用视为带有测试和返回或调用的一次迭代。
I'm going to operate under the assumption that this is homework, if I'm wrong I'll come back and edit this post or repost.
Firstly, you should try to write your factorial function in a tail recursive manner. Though it probably won't make much difference in C, it's good practice.
Next, you don't generally want to put a loop inside of your recursive functions, that somewhat defeats the point. Think of a recursive call as one iteration with a test and either return or recall.
由于您正在执行浮点运算。不同的实施方式可以产生不同的结果。
就您的情况而言,我可以想到发生损失的一个地方
不等于
了解更多信息,
http://en.wikipedia.org/wiki/Floating_point#Multiplication
Since you are performing floating point arithmetic. Different ways of implementation can produce different results.
In your case i can think of one place where losses are incurred
is not equal to
For more information,
http://en.wikipedia.org/wiki/Floating_point#Multiplication