PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php function closestToZero(array $ts) { // If the array is empty, return 0 if (empty($ts)) { return 0; } // Initialize the closest temperature $closest = $ts[0]; // Iterate through each temperature in the array foreach ($ts as $temp) { print($temp, $closest); // Check if the current temperature is closer to zero if (abs($temp) < abs($closest) || (abs($temp) == abs($closest) && $temp > $closest)) { $closest = $temp; } } // Return the closest temperature to zero return $closest; } // Test cases $ts1 = [-1.7, 1.7, -1, 1, 0.5, -0.5]; // Expected output: -1.7 $ts2 = [5, -5, -4, 4, 3.5, -3.5]; // Expected output: 3.5 $ts3 = []; // Expected output: 0 $ts4 = [-273, 5526]; // Expected output: -273 echo closestToZero($ts1) . "\n"; echo closestToZero($ts2) . "\n"; echo closestToZero($ts3) . "\n"; echo closestToZero($ts4) . "\n"; ?>
Show:  
Copy Clear