You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现底部宽度为输入值一半的箭头图形:现有代码问题修正需求

Got it, let's fix this arrow shape issue. The main problem with your original code is that it checks individual discrete positions instead of continuous ranges, and the logic for the lower half of the arrow is misaligned with your expected output. Here's the corrected PHP code that produces exactly the shape you want:

$input = 7;
$mid = ($input + 1) / 2; // Middle position of the arrow (4 for input=7)
$bottomStarCount = floor($input / 2); // Number of stars in the lower arrow section (3 for input=7)
$bottomOffset = ($bottomStarCount - 1) / 2; // Range offset for the lower stars (1 for 3 stars)

for ($i = 1; $i <= $input; $i++) {
    for ($j = 1; $j <= $input; $j++) {
        if ($i <= $mid) {
            // Top half: incrementally expand stars from center
            $currentOffset = $i - 1;
            echo ($j >= $mid - $currentOffset && $j <= $mid + $currentOffset) ? "*" : "_";
        } else {
            // Bottom half: keep fixed 3 stars in the center
            echo ($j >= $mid - $bottomOffset && $j <= $mid + $bottomOffset) ? "*" : "_";
        }
    }
    echo "<br>";
}

Key Fixes & Explanations:

  1. Continuous Range Checks: Instead of checking isolated positions, we now verify if each column $j falls within a continuous range around the center. This fixes the scattered stars in your original output and creates the smooth expanding arrow head.
  2. Split Logic for Top/Bottom:
    • Top half (first 4 rows for input=7): We expand the star range outward by 1 column per row, starting with 1 star and growing to the full width of the input.
    • Bottom half (last 3 rows for input=7): We lock the star range to the center 3 columns, matching your expected repeating middle-star pattern.
  3. Style Alignment: Swapped the original - separator for _ to match your desired output format.
  4. Readable Variable Names: Renamed variables to clearly describe their purpose, making the code easier to adjust for different input values later.

When you run this code, it will output exactly what you requested:

___*___
__***__
_*****_
*******
__***__
__***__
__***__

内容的提问来源于stack exchange,提问作者ComSci_Professor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:12:43