0

I was making a code that adds a summation for a specific formula, but the sum is always 0 for some reason. What is the reason nothing is adding? I think maybe it is the declaration of int and double for the variables. When I do a simple equation, such as adding natural numbers, it works, but not for more complicated equations like the one below.

Code:

#include <stdio.h>

int main()
{
    int i, n;
    double sum = 0;
    printf("Enter the max value for the sum: ");
    scanf("%d", &n);
    i = 1;

    while(i <= n)
    {
        sum = sum + (1 / ((1 + i) * (1 + i)));
        i++;
    }
    printf("Sum = %f\n", sum);  
}

I tried the code pasted above, expected the correct sum, but resulted in only 0.0000.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

2 Answers2

1

In this statement

sum = sum + (1 / ((1 + i) * (1 + i)));

the sub-expression (1 / ((1 + i) * (1 + i))) uses the integer arithmetic. It means that if to divide 1 by any integer number greater than 1 the result will be equal to 0.

Consider this simple demonstration program

#include <stdio.h>

int main( void )
{
    int i = 1;

    i = i / 2;

    printf( "i = %d\n", i );
}

Its output is

i = 0

You need to use the arithmetic with float numbers.

It will be enough to write

sum += 1.0 / ((1 + i) * (1 + i));

Or it will be even more better to write using long long int constant 1ll within the expression like

sum += 1.0 / ((1ll + i) * (1ll + i));

to avoid overflow for the integer multiplication.

Also as the range is specified as two positive numbers then it will be logically better to specify the variables i and n as having the type unsigned int.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You need to cast the result of the divison as a double since that is what you are expecting as a result. Int division will round it to closest whole number

kalle konsida
  • 323
  • 2
  • 5
  • 12