亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 php 中反轉 while 循環輸出的順序

如何在 php 中反轉 while 循環輸出的順序

PHP
陪伴而非守候 2022-08-19 10:18:06
我的目標是將十進制整數轉換為二進制,如本視頻中所述,http://youtu.be/XdZqk8BXPwg 使用php函數,我知道php可以使用內置的decbin()開箱即用,但無論如何我都想寫一個。<?phpfunction decToBin($int) {$roundInt = intval($int) * 2;    while ($roundInt > 1) {        $result = intval($roundInt = $roundInt / 2);        if ($result % 2 == 0) {            $result = 0;        } else {            $result = 1;        }        echo $result;    }}decToBin(123);我嘗試在循環時,但我得到的結果顛倒了。有沒有辦法我可以反轉,所以不是11011110我得到01111011,或者沒有前面的零更好。謝謝
查看完整描述

3 回答

?
慕的地8271018

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;

}


查看完整回答
反對 回復 2022-08-19
?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

只是你在這里做錯了幾件事:

  1. 您有一個舍入錯誤(使用intdiv進行整數除法,而不是您正在執行的操作,這會產生復合效應)。

  2. 指定實際的類型隱藏而不是強制轉換(確保類型安全)

  3. 從函數返回實際值,不輸出(保留對其最終組合的控制)

以下是您的函數的實際外觀...

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"


查看完整回答
反對 回復 2022-08-19
?
繁星點點滴滴

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


查看完整回答
反對 回復 2022-08-19
  • 3 回答
  • 0 關注
  • 119 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號