1

everyone,c primer plus chapter 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;
}

what's wrong about my code?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Felord
  • 11
  • 2
  • 3
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – too honest for this site Sep 27 '16 at 10:28
  • 2
    Possible duplicate of [Is this algorithm to find the sum to infinity of a series acceptable?](http://stackoverflow.com/questions/35861210/is-this-algorithm-to-find-the-sum-to-infinity-of-a-series-acceptable) – progyammer Sep 27 '16 at 10:44
  • You need to describe at least till what limit it works fine or whether it works at all – Vinay Sep 27 '16 at 11:05

1 Answers1

1

Here :

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

You assign the value of b to d (by d = b), then, you check if this value modulo 2 is equal to 1. If it's the case, you go inside your loop forever as the value of b never changes. Of course you increment d inside your loop, but in your check, you reset its value to b, leading to an infinite loop.

Regarding your exercice, you're trying to set c to -1 if b is even and to 1 is b is odd. This can easily be done with a conditional assignment :

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

Or, as the hint in your question suggests, you can initialize c to 1 (or -1) before you ener the loop and do c = -1.0 * c inside

Thomas W.
  • 460
  • 3
  • 9