duanlaican1849 2019-02-18 07:21
浏览 104
已采纳

为什么我需要括号来表达简单?

Why do I need the brackets to add $a + $b below:

<?php declare(strict_types=1);
function addNumbers(float $a, float $b) : int {
    return (int)($a + $b);
}
echo addNumbers(1.2, 5.2); 
?>

The used of brackets in cases like this confuses me. Why is an error thrown if the $a + $b isn't surrounded by brackets? It may be a simple question but study material often doesn't explain detail. Any clarity would be appreciated.

  • 写回答

2条回答 默认 最新

  • doudao1369 2019-02-18 07:24
    关注

    Without the () around $a + $b, the code is interpreted as

    return ((int)$a) + $b;
    

    because the operator precedence of (int) is higher than that of + (see the manual) which in this case would be

    ((int)1.2) + 5.2
    =>
    1 + 5.2
    =>
    6.2
    

    Even though the first value in this expression is an int, because the second is a floating point number, PHP will perform type juggling and convert the first value to a float as well, thus the result of the expression is a floating point number, which cannot be returned by addNumbers as it is declared to return an int.

    By putting the () in, the expression is interpreted as

    (int)(1.2+5.2)
    =>
    (int)6.4
    =>
    6
    

    which is ok to be returned.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题