+ 2
for 1=i<=10 (sum+=1/i )
I really don't get how this code works if someone could please explain it to me, step by step, that would be great. Thanks. https://code.sololearn.com/clGLW2pLnyhL/?ref=app
4 ответов
+ 2
The following lines
for( i=1;i<=10;i++)
sum+=1/i;
do the following:
On the first iteration of the loop,
i is 1, so adds up 1 to sum.
Then on the following iterations of the loop it attempt to add a fraction <1
but since i is an integer it adds 0.
so in the end when printing sum, it prints 1.0.
If you change i to be a float you will see sum incremented by 1/2 + 1/3 + etc...
+ 1
but is it not the point of the double to store numbers with digits beyond decimal point?
0
yes and it does( it prints 1.0 rather than just 1) but because i is an integer you never add the decimals to sum in the loop, 1/i is always rounded down to zero for i>1.
0
so, to store a doble every variable in equation has to be a double. Thank you for your answer.