我不确定我错过了什么,但我无法得到 $c 以正确输出。

<?php

function pythThm($a, $b){
    $a2 = pow($a, 2);
    $b2 = pow($b, 2);
    $c = sqrt($a2 + $b2);
    if(is_int($c)){return $c;}
}

echo pythThm(3, 4);
//outputs nothing, should be 5

?>

我为初学者的问题道歉。

问题的解决方案:

<?php
function pythThm($a, $b){
$a2 = pow($a, 2);
$b2 = pow($b, 2);
$c = sqrt($a2 + $b2);
if($c - round($c) == 0){return $c;}
}

echo pythThm(4, 4); 
//returns nothing
echo pythThm(3,4);
//returns 5
?>

感谢所有回答的人。..我会确保下次阅读有关该功能的完整信息!

有帮助吗?

解决方案

sqrt 返回a float, ,这不是一个 int, ,所以你的函数什么都不返回。把 is_int 支票?

其他提示

sqrt 总是返回一个浮点数。你的if语句总是错误的。

如果你想做检查,这样做:

$i = (int) $c;

if($c == $i) return $c

这样做的是将浮点数转换为int,如果浮点数 $c 和int $i 相等,那么它就会返回

sqrt 返回a float, ,这就是为什么 is_int 总是假的。

如果你真的想检查它是否是整数,你可以使用:

if ((int)$c == $c)
    return $c;

这是你的结果中的错字

function pythThm($a, $b){
    $a2 = pow($a, 2);
    $b2 = pow($b, 2);
    $c = sqrt($a2 + $b2);
    return (int)$c;
}

echo pythThm(3, 4);
<?php

function pythThm($a, $b){
    $a2 = pow($a, 2);
    $b2 = pow($b, 2);
    $c =  sqrt($a2 + $b2);
   return $c;
}

echo pythThm(3, 4);
//outputs nothing, should be 5

?>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top