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

PHP数组任务:计算游戏标题平均长度与平均价格(需for循环和number_format)

解决PHP数组的平均价格与标题平均长度计算问题

以下是完全符合要求的代码实现,使用了for循环和number_format函数:

<?php
$games = [
    ["Call of Duty", "Shooter", 59.95],
    ["Rocket League", "Sport", 19.95],
    ["Assassins Creed", "RP", 49.95]
];

// 初始化总价格、总标题长度和游戏数量变量
$totalPrice = 0;
$totalTitleLength = 0;
$gameCount = count($games);

// 用for循环遍历所有游戏
for ($i = 0; $i < $gameCount; $i++) {
    // 累加每个游戏的价格(子数组索引2对应价格)
    $totalPrice += $games[$i][2];
    // 累加每个标题的字符串长度(子数组索引0对应标题)
    $totalTitleLength += strlen($games[$i][0]);
}

// 计算平均值
$averagePrice = $totalPrice / $gameCount;
$averageTitleLength = $totalTitleLength / $gameCount;

// 用number_format格式化输出,保留2位小数
echo "average price: €" . number_format($averagePrice, 2) . "\n";
echo "average length of titles: " . number_format($averageTitleLength, 2);
?>

关键步骤说明:

  • 先用count($games)获取游戏总数,避免在循环中重复计算,提升效率。
  • for循环从索引0开始遍历数组,每个子数组的索引0是游戏标题,索引2是价格,分别用strlen()取长度、直接取数值进行累加。
  • 计算平均值时用总和除以游戏数量,再用number_format()统一格式化小数位数,确保输出的数值规范易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:30:43