D
D
dandropov952018-09-17 20:32:54
C++ / C#
dandropov95, 2018-09-17 20:32:54

How to write a program to find the "sum" of values ​​in a sequence?

There is such a task from the book:
5b9fe3b61d104857982490.png
Please explain what exactly is required to find in this task?
And explain why the "Hint" is indicated in the text of the problem?
And it is not clear to what value the sequences should converge. (if they should at all)
I sort of wrote a solution, but something doesn't seem right.

Solution 1
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <conio.h>

int main(void)
{
  float value = 1.0;
  int length;
  float result_1 = 0.0;
  float result_2 = 0.0;
  float number = 1.0;

  printf("Input length: ");

  while (scanf("%d", &length) == 1 && length > 0)
  {
    for (int i = 0; i < length; i++, number++)
    {
      result_1 += (value / number);

      if (i % 2 == 0)
        result_2 += (value / number);
      else
        result_2 -= (value / number);
    }

    printf("1.0 + 1.0 / 2.0 + ... = %f\n", result_1);
    printf("1.0 - 1.0 / 2.0 + ... = %f\n", result_2);
    printf("Input the next length: ");
  }

  printf("Done!");

  _getch();

  return 0;
}

Solution 2
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <conio.h>

int main(void)
{
  float value = 1.0;
  int length;
  float result_1 = 0.0;
  float result_2 = 0.0;
  float number = 1.0;

  printf("Input length: ");

  while (scanf("%d", &length) == 1 && length > 0)
  {
    for (int i = 0; i < length; i++, number++)
    {
      result_1 += (value / number);
    }

    number = 1.0;

    for (int i = 0; i < length; i++, number++)
    {
      if (i % 2 == 0)
        result_2 += (value / number);
      else
        result_2 -= (value / number);
    }

    printf("1.0 + 1.0 / 2.0 + ... = %f\n", result_1);
    printf("1.0 - 1.0 / 2.0 + ... = %f\n", result_2);
    printf("Input the next length: ");
  }

  printf("Done!");

  _getch();

  return 0;
}


It seems like the results should match, but for some reason the results of running the two solutions are different. Can you please tell me why the results are different (MSVC)? It's just that the calculations are divided into two cycles with the same conditions.
PS. Compiled both options with another compiler (GCC). The result was the same in both cases. Why is that?
P.S.S. Something I'm completely confused. I tried to write "the same thing" in slightly different ways, in the end all the results turned out to be different.
I tried first in the second loop to replace i with j. The result is different. Then I tried to bring the variables to the default value before the second loop. The end result is another result.
It feels like at startup, the cycles work in a jumble and all the data is mixed into a heap ...

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question