PHP生成器脚本累加逻辑疑问:为何输出不符合预期步长结果?
Hey Tom, let's walk through exactly what's happening in this generator function to clear up why you're seeing 6 instead of 4 as the second output!
First, let's recap the key part of your code that's driving the output:
function addieren($start, $ende, $schritt = 1) { if ($start < $ende) { $erg = 0; for ($i = $start; $i <= $ende; $i += $schritt) { $erg += $i; // This line is the critical piece yield $erg; } } }
The confusion comes from what yield is returning here—it's not the current value of $i, but the running total stored in $erg. Let's break down each iteration of the loop when you call addieren(2, 10, 2):
First iteration:
- $i starts at 2
- $erg (initially 0) becomes 0 + 2 = 2
- Yield 2 → this is your first output
Second iteration:
- $i increments by 2 to 4
- $erg (now 2) becomes 2 + 4 = 6
- Yield 6 → this is why you see 6 instead of 4
Third iteration:
- $i increments to 6
- $erg becomes 6 + 6 = 12 → yield 12
Fourth iteration:
- $i increments to 8
- $erg becomes 12 + 8 = 20 → yield 20
Fifth iteration:
- $i increments to 10
- $erg becomes 20 + 10 = 30 → yield 30
If you were expecting the output to be 2, 4, 6, 8, 10 (just each step value), you'd want to yield $i directly instead of the running total:
function addieren($start, $ende, $schritt = 1) { if ($start < $ende) { for ($i = $start; $i <= $ende; $i += $schritt) { yield $i; // Yield the current step value instead of the sum } } }
That makes sense now, right? The original code is designed to return cumulative sums, not individual step values.
内容的提问来源于stack exchange,提问作者Tom

