3 回答

TA貢獻1796條經驗 獲得超4個贊
與其一次一個位地回顯結果,不如通過在左側添加新值來構建一個字符串:
<?php
function decToBin($int) {
$roundInt = intval($int) * 2;
$output = '';
while ($roundInt > 1) {
$result = intval($roundInt = $roundInt / 2);
if ($result % 2 == 0) {
$result = 0;
} else {
$result = 1;
}
$output = $result . $output;
}
echo $output;
}

TA貢獻1865條經驗 獲得超7個贊
只是你在這里做錯了幾件事:
您有一個舍入錯誤(使用
intdiv
進行整數除法,而不是您正在執行的操作,這會產生復合效應)。指定實際的類型隱藏而不是強制轉換(確保類型安全)
從函數返回實際值,不輸出(保留對其最終組合的控制)
以下是您的函數的實際外觀...
function decToBin(Int $int): String {
$bin = ""; // Initialize the return value
$roundInt = $int * 2;
while ($roundInt > 1) {
$roundInt = $result = intdiv($roundInt, 2); // Safe integer division
$result &= 1;
$bin = $result . $bin; // Compose with byte endianness at LSB first
}
return $bin;
}
var_dump(decToBin(123));
現在您得到實際的正確結果...
string(7) "1111011"

TA貢獻1803條經驗 獲得超3個贊
我對現有代碼進行了最小的更改,而無需更改方法。您可以使用 strrev 函數來反轉輸出。這里,數據被附加到$return_data,它返回并存儲在$returned_data中,然后使用strrev預定義函數。
function decToBin($int) {
$roundInt = intval($int) * 2;
$return_data ='';
while ($roundInt > 1) {
$result = intval($roundInt = $roundInt / 2);
if ($result % 2 == 0) {
$result = 0;
} else {
$result = 1;
}
$return_data .=$result; //Data appending
}
return $return_data; //returns
}
$returned_data = decToBin(123);
echo strrev($returned_data); //reverse function
- 3 回答
- 0 關注
- 119 瀏覽
添加回答
舉報