PHP函数调试求助:按规则生成数值序列逻辑错误
Fixing the
getDenominations() PHP Function for $max > 100 Got it, let's get this function working as expected! The issue right now is that when $max > 100, your code skips the 20-to-100 step-by-5 sequence entirely and starts incrementing by 25 right from 20. That's why your output for $max=500 isn't including those smaller denominations.
Here's the corrected code that follows your requirements perfectly:
public function getDenominations($max) { $start = 20; $output = []; // First, handle the 20 to min(max, 100) range with step 5 $upperStep5 = min($max, 100); for($i = $start; $i <= $upperStep5; $i += 5) { array_push($output, $i); } // If max is over 100, add denominations from 125 onward with step 25 if($max > 100) { // Start at 125 since 100 is already included in the previous loop for($i = 125; $i <= $max; $i += 25) { array_push($output, $i); } } return $output; }
How this works:
- Unified step-5 logic: Instead of splitting the step-5 loop into two separate cases, we use
min($max, 100)to cap the upper limit. This way, if$max <=100, we just go up to$max; if it's over 100, we go up to 100. No duplicate code needed! - Step-25 extension: When
$max >100, we start the step-25 loop at 125 (since 100 is already in the array from the step-5 loop) and keep going until we hit$max.
Testing this with $max=500 will give you the full sequence: 20,25,...,100,125,150,...,500 — exactly what you're expecting.
内容的提问来源于stack exchange,提问作者SBB
相关产品推荐
相关产品推荐

