+ 1
Why does my code print the original sum value, and not what it's supposed to be?
My code is meant to calculate: 1-1/2+1/4-1/6+1/8-1/10......+1/20 https://code.sololearn.com/cvd32684nn3j/?ref=app Thanks in advance:) Edit: I changed all the variables to double, and it worked :D
2 Respostas
+ 2
i think its because the operation are in integer, thus its rounding up(or down, i dont remember) the result.
change the sum type into float or double, also cast the divisor fom the division operation
+ 7
sum=sum+sign*(1/i);
In this expression 1/i will be 0 for every i>1 and being a whole number, to avoid it you can use float or double type here, same for variable sum as it will not be a whole number in general.
Benan Essayed
you can use 1.0/i and make variable sum float type(which you already done) OR make i in float type too.