Haskell程式:十進位制轉換為二進位制


在 Haskell 中,我們將使用 reverse 函式、尾遞迴和 divMod 函式將十進位制轉換為二進位制。在第一個示例中,我們將使用 (decToBin n | n < 0 = error "Input must be non-negative" | n == 0 = "0" | otherwise = reverse $ decToBin' n) 函式,在第二個示例中,我們將使用 (binDigits 0 = "" and binDigits n = let (q, r) = n `divMod` 2 in show r ++ binDigits q) 函式。

方法 1:使用 reverse 函式和尾遞迴

在這種方法中,decToBin 函式接受一個整數 n 作為輸入,並返回 n 的二進位制表示形式(字串)。該函式首先檢查輸入 n 是否是非負數。如果 n 為負數,則引發錯誤。如果 n 為零,則返回字串“0”。否則,它將呼叫帶有 n 的 decToBin' 輔助函式,然後反轉結果字串。

演算法

  • 步驟 1 − 匯入 Data.Char 庫。

  • 步驟 2 − 使用 reverse 函式定義 decToBin 函式,如下所示:

decToBin n
   | n < 0     = error "Input must be non-negative"
   | n == 0    = "0"
   | otherwise = reverse $ decToBin' n.

The helper decToBin’ function is defined as,
decToBin' n
   | n == 0    = ""
   | otherwise = show (n `mod` 2) ++ decToBin' (n `div` 2).
  • 步驟 3 − 程式執行將從 main 函式開始。main() 函式控制整個程式。它被寫成 main = do。在 main 函式中,decToBin 函式被呼叫並帶有一個引數,結果被列印到控制檯。

  • 步驟 4 − 初始化名為“n”的變數。它將儲存要轉換為相應二進位制數的十進位制數。

  • 步驟 5 − 函式呼叫後,使用‘putStrLn’語句將結果二進位制數列印到控制檯。

示例 1

在這個示例中,使用 reverse 函式定義了尾遞迴函式來將十進位制數轉換為二進位制數。

decToBin :: Integer -> String
decToBin n
   | n < 0     = error "Input must be non-negative"
   | n == 0    = "0"
   | otherwise = reverse $ decToBin' n

decToBin' :: Integer -> String
decToBin' n
   | n == 0    = ""
   | otherwise = show (n `mod` 2) ++ decToBin' (n `div` 2)

main :: IO ()
main = do
   let n = 15
   putStrLn $ "The binary representation of " ++ show n ++ " is " ++ decToBin n

輸出

The binary representation of 15 is 1111

方法 2:使用 divMod 函式

在這種方法中,使用輔助函式 binDigits 遞迴生成輸入數字的二進位制數字。binDigits 函式接受輸入數字 n 並返回 n 的二進位制數字(字串)。這些數字是透過重複將 n 除以 2 並取餘數生成的。結果以相反的順序累積為字串,使用 show r 將餘數轉換為字串。

演算法

  • 步驟 1 − 使用 reverse 函式定義 decToBin 函式,如下所示:

decToBin n
   | n < 0     = error "Input must be non-negative"
   | n == 0    = "0"
   | otherwise = reverse $ binDigits n.

The recursive binDigits function is defined using divMod function as,
binDigits 0 = ""
binDigits n = let (q, r) = n `divMod` 2
              in show r ++ binDigits q.
  • 步驟 2 − 程式執行將從 main 函式開始。main() 函式控制整個程式。它被寫成 main = do。在 main 函式中,decToBin 函式被呼叫並帶有一個引數,結果被列印到控制檯。

  • 步驟 3 − 初始化名為“n”的變數。它將儲存要轉換為相應二進位制數的十進位制數。

  • 步驟 4 − 函式呼叫後,使用‘putStrLn’語句將結果二進位制數列印到控制檯。

示例 1

在這個示例中,使用 divMod 函式定義了遞迴函式來將十進位制數轉換為二進位制數。

decToBin :: Integer -> String
decToBin n
   | n < 0     = error "Input must be non-negative"
   | n == 0    = "0"
   | otherwise = reverse $ binDigits n

binDigits :: Integer -> String
binDigits 0 = ""
binDigits n = let (q, r) = n `divMod` 2
              in show r ++ binDigits q
main :: IO ()
main = do
   let n = 15
   putStrLn $ "The binary representation of " ++ show n ++ " is " ++ decToBin n

輸出

The binary representation of 52 is 1111

結論

在 Haskell 中,十進位制數轉換為二進位制數可以使用 reverse 函式結合尾遞迴,或者使用 divMod 函式。將十進位制數轉換為二進位制數的過程涉及重複將十進位制數除以 2 並取餘數。然後以相反的順序讀取餘數,以獲得十進位制數的二進位制等效值。

更新於: 2023年3月13日

740 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告