gpt4 book ai didi

c primer plus 第 6 章 ex12

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:56 25 4
gpt4 key购买 nike

每个人,c primer 加上第 6 章 ex12:

**Consider these two infinite series:

1.0 + 1.0/2.0 + 1.0/3.0 + 1.0/4.0 + ...

1.0 - 1.0/2.0 + 1.0/3.0 - 1.0/4.0 + ...

Write a program that evaluates running totals of these two series up to some limit of number of terms. Hint: –1 times itself an odd number of times is –1, and –1 times itself an even number of times is 1. Have the user enter the limit interactively; let a zero or negative value terminate input. Look at the running totals after 100 terms, 1000 terms, 10,000 terms. Does either series appear to be converging to some value?**

#include <stdio.h>
int main(void)
{
int times, a, b, d;
float sum1, sum2, c;
printf("Enter the times: ");
scanf("%d", &times);
while (times > 0)
{
sum1 = 0;
sum2 = 0;

for (a = times; a >= 1; a--)
sum1 += 1.0 / (float)a;
printf("The sum1 is %f\n", sum1);


for (b = times; b >= 1; b--)
{
c = -1.0;
while ((d = b) % 2 == 1)
{
c = 1.0;
d++;
}
sum2 += (c / (float)b);
}
printf("The sum2 is %f\n", sum2);

printf("Enter the times again: ");
scanf("%d", &times);
}
return 0;
}

我的代码有什么问题?

最佳答案

这里:

while ((d = b) % 2 == 1)
{
c = 1.0;
d++;
}

您将 b 的值赋给 d(通过 d = b),然后,您检查此值对 2 的模数是否相等到 1。如果是这种情况,您将永远进入循环,因为 b 的值永远不会改变。当然,您在循环内递增 d,但在您的检查中,您将其值重置为 b,从而导致无限循环。

关于你的练习,如果 b 是偶数,你试图将 c 设置为 -1,如果 b 是奇数,则设置为 1。这可以通过条件赋值轻松完成:

c = (b % 2 == 0) ? -1.0 : 1.0;

或者,正如您问题中的提示所暗示的,您可以在启动循环之前将 c 初始化为 1(或 -1)并在里面做 c = -1.0 * c

关于c primer plus 第 6 章 ex12,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39722259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com