乘以二和除以二
为什么这两段代码给出两个不同的结果?
double sum = 1.0;
double xSqFour = x * x / 4;
for (int i = 48; i > 1; i-=2) {
sum = 1.0 + (xSqFour / ((i/2) * (i/2))) * sum;
}
return sum;
和
double sum = 1.0;
double xSqFour = x * x / 4;
for (int i = 24; i > 1; i--) {
sum = 1.0 + (xSqFour / (i * i)) * sum;
}
return sum;
Why are these two snippets of code giving two different results?
double sum = 1.0;
double xSqFour = x * x / 4;
for (int i = 48; i > 1; i-=2) {
sum = 1.0 + (xSqFour / ((i/2) * (i/2))) * sum;
}
return sum;
and
double sum = 1.0;
double xSqFour = x * x / 4;
for (int i = 24; i > 1; i--) {
sum = 1.0 + (xSqFour / (i * i)) * sum;
}
return sum;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第二个循环出现边界错误。应该是
i > 0 。第一个循环有
i >; 1
,但它也将i
除以 2。1 / 2 == 0
,所以它应该是i > 1。 0 在第二个循环中。
You have a bounds error on your second loop. It should be
i > 0
. The first loop hasi > 1
, but it also dividesi
by 2.1 / 2 == 0
, so it should bei > 0
in the second loop.