0

Im trying to sum the multiples of a number (x0) with a progression number (r) and a number of times (n). If I use the number x0 = 6, r = 3, n = 3, the result should be 6+9+12=27, but the program gives me always 18.

I try different times changing the formula but if I do on the paper the result is right, so Im afraid the problem can be the syntax...

So theres the program in C:

#include <stdio.h>

int sum_progression(int x0, int r, int n)
{
  return (n/2) * ((2 * x0) + ((n - 1) * (r)));
}

void test_sum_progression(void)
{
  int x0;
  int r;
  int n;
  scanf("%d", &x0);
  scanf("%d", &r);
  scanf("%d", &n);
  int z = sum_progression(x0,r,n);
  printf("%d\n", z);
}

int main(void)
{
  test_sum_progression();
  return 0;
}

Thanks for helping!

sepp2k
  • 363,768
  • 54
  • 674
  • 675

1 Answers1

1

When using ints with division the value is calculated and then truncated to int.
if you divide int by int you should do something like:
return (n/(double)2) * ((2 * x0) + ((n - 1) * (r)));

atlanteh
  • 5,615
  • 2
  • 33
  • 54