Question

I'm not sure what I'm missing, but I can't get $c to output correctly.

<?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

?>

I apologize for the beginner question.

Solution to problem:

<?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
?>

Thanks to all who answered...I'll make sure to read the full info about the function next time!

Was it helpful?

Solution

sqrt returns a float, which is not an int, so your function returns nothing. Just leave off the is_int check?

OTHER TIPS

sqrt always returns a float. Your if statement is always false.

If you want to do the check, do this:

$i = (int) $c;

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

What this does is cast the float to an int, and if the float $c and the int $i are equal, then it will return

sqrt returns a float, that's why is_int is always false.

If you really want to check if it's an integer, you can use:

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

That is typo in your result

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

?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top