我正在尝试进行一项活动,我需要以cm为单位放置一个数字,程序必须以km,m和cm返回它。
一个例子: 270004 cm = 2km,700m,4cm // 100cm = 0km,1m,0cm。
我已经完成了这段代码,但是,有时我会得到负数,有时我会得到奇怪的数字。
也许是我使用PHP_ROUND_HALF_UP
??
我能做些什么来解决它?
//I have an HTML form to introduce the number value
$num = 123456789;
$km = $num/1000;
$km = round($km, 0, PHP_ROUND_HALF_UP);
echo "km: ".$km."<br>";
$subtraction = ($km * 1000) - $num;
$m = $subtraction / 100;
$m = round($m, 0, PHP_ROUND_HALF_UP);
echo "m: ".$m."<br>";
$subtraction2 = ($m * 100) - $subtraction;
$cm = $subtraction2;
echo "cm: ".$cm."<br>";
答案 0 :(得分:7)
老实说,你的代码似乎有点过于复杂:P听说过模数除法吗?在这里派上用场!
<?php
$x = 123456789323; // centimeters
$km = floor($x / 100000); // amount of "full" kilometers
$rkm = $x % 100000; // rest
$m = floor($rkm / 100); // amount of "full" meters"
$cm = $rkm % 100; // rest
echo $x . ' cm = ' . $km . ' kilometers ' . $m . ' meters and ' . $cm . 'centimeters' . PHP_EOL;
答案 1 :(得分:2)
$cm = 234459891345;
echo sprintf('km: %02d m: %02d cm: %02d', ($cm/100000),($cm/100%100), $cm%100);