PKR 发表于 2022-10-16 08:32:32

为什么是45不是44

第一次循环不是先执行sum吗所以i是1那不应该sun是1吗然后在算i是2这样推到最后sum不是45吗

新月流水 发表于 2022-10-16 08:36:42

没问题,是45啊

jackz007 发表于 2022-10-16 08:50:32

sum = 1 + 2 + 3 + 4+ 5 + 6 + 7 + 8 + 9 = (1 + 9) * 9 / 2 = 90 / 2 = 45

PKR 发表于 2022-10-16 08:52:53

新月流水 发表于 2022-10-16 08:36
没问题,是45啊

怎么推的 第一次sum不是1吗第二次不是3吗

hveagle 发表于 2022-10-16 09:06:10

0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
10 + 5 = 15
15 + 6 = 21
21 + 7 = 28
28 + 8 = 36
36 + 9 = 45

tommyyu 发表于 2022-10-16 09:32:42

PKR 发表于 2022-10-16 08:52
怎么推的 第一次sum不是1吗第二次不是3吗

他不就是0+1+2+3+4+5+6+7+8+9 = 45么

Twilight6 发表于 2022-10-16 09:37:10




第一次循环: i = 1 , sum = 0--->sum = sum + i = 0 + 1 = 1, i = i + 1 = 1 + 1 = 2

第二次循环: i = 2 , sum = 1---> sum = sum + i = 1 + 2 = 3,i = i + 1 = 2 + 1 = 3

第三次循环: i = 3 , sum = 3---> sum = sum + i = 3 + 3 = 6,i = i + 1 = 3 + 1 = 4

第四次循环: i = 4 , sum = 6---> sum = sum + i = 6 + 4 = 10,i = i + 1 = 4 + 1 = 5

第五次循环: i = 5 , sum = 10---> sum = sum + i = 10 + 5 = 15,i = i + 1 = 5 + 1 = 6

第六次循环: i = 6 , sum = 15---> sum = sum + i = 15 + 6 = 21,i = i + 1 = 6 + 1 = 7

第七次循环: i = 7 , sum = 21---> sum = sum + i = 21 + 7 = 28,i = i + 1 = 7 + 1 = 8

第八次循环: i = 8 , sum = 28---> sum = sum + i = 28 + 8 = 36,i = i + 1 = 8 + 1 = 9

第九次循环: i = 9 , sum = 36---> sum = sum + i = 36 + 9 = 45,i = i + 1 = 9 + 1 = 10

第十次循环: i = 10 , sum = 45 ---> 不满足 while 循环条件,退出循环,所以最终 sum 的值为 45


页: [1]
查看完整版本: 为什么是45不是44