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.
CodePudding user response:
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
.
'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
like
sum = 1.0 / ((1ll i) * (1 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
.
CodePudding user response:
Check how division of ints is defined.
CodePudding user response:
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