Haskell程式計算數字的冪


本教程討論了在Haskell程式語言中編寫計算數字冪的程式。

一個數字的n次冪是指將該數字自身乘以n次的數值。

數字的冪可以用指數形式“a^n”表示,a被提升到n次冪。其中a稱為底數,n稱為指數。例如,2的5次冪為2^5,即32。

在本教程中,我們將看到實現計算數字冪的程式的不同方法。

  • 使用運算子“^”計算數字冪的程式。
  • 使用運算子“^^”計算數字冪的程式。
  • 使用運算子“**”計算數字冪的程式。
  • 使用運算子“*”計算數字冪的程式。

演算法步驟

  • 獲取輸入或初始化變數。
  • 實現計算數字冪的程式邏輯。
  • 列印或顯示輸出。

示例1

使用運算子“^”計算數字冪的程式

main :: IO()
main = do
-- initializing and declaring variable for base and exponent
   let base = 2
   let expo = 5
-- computing the power and printing the output
   print (show base ++ " raised to the power of " ++ show expo ++ " is:")
   print (base^expo)

輸出

"2 raised to the power of 5 is:"
32

在上面的程式中,我們宣告並初始化了底數和指數的變數,分別為base和expo,其值為2和5。我們使用運算子“^”計算了底數的冪。最後,我們使用print函式列印了輸出。運算子“^”的函式宣告為 (^) :: (Num a, Int b) => a -> b -> a。底數可以是整數或浮點數,指數必須是整數。

注意 − show函式用於將數字解析為字串。此函式接收一個數字引數並返回一個字串。“++”是Haskell中用於連線字串的運算子。

示例2

使用運算子“^^”計算數字冪的程式

main :: IO()
main = do
-- initializing and declaring variable for base and exponent
   let base = 2.1
   let expo = 5
-- computing the power and printing the output
   print (show base ++ " raised to the power of " ++ show expo ++ " is:")
   print (base^^expo)

輸出

"2.1 raised to the power of 5 is:"
40.841010000000004

在上面的程式中,我們宣告並初始化了底數和指數的變數,分別為base和expo,其值為2.1和5。我們使用運算子“^^”計算了底數的冪。最後,我們使用print函式列印了輸出。運算子“^^”的函式宣告為 (^^) :: (Float a, Int b) => a -> b -> a。底數為浮點數,指數必須是整數。

示例3

使用運算子“**”計算數字冪的程式

main :: IO()
main = do
-- initializing and declaring variable for base and exponent
   let base = 2.1
   let expo = 5.2
-- computing the power and printing the output
   print (show base ++ " raised to the power of " ++ show expo ++ " is:")
   print (base**expo)

輸出

"2.1 raised to the power of 5.2 is:"
47.374030205310675

在上面的程式中,我們宣告並初始化了底數和指數的變數,分別為base和expo,其值為2.1和5.2。我們使用運算子“**”計算了底數的冪。最後,我們使用print函式列印了輸出。運算子“**”的函式宣告為 (**) :: (Float a) => a -> a -> a。底數為浮點數,指數為浮點數。

示例4

使用運算子“*”計算數字冪的程式

-- function declaration
power :: Int->Int->Int
-- function definition
-- base case 1
power base 0 = 1
-- base case 2
power base 1 = base
power base expo = base*(power base (expo-1))
main :: IO()
main = do
-- initializing and declaring variable for base and exponent
   let base = 2
   let expo = 5
-- computing the power and printing the output
   print (show base ++ " raised to the power of " ++ show expo ++ " is:")
   print (power base expo)

輸出

"2 raised to the power of 5 is:"
32

在上面的程式中,我們聲明瞭一個名為power的函式,它接收兩個整數引數並返回一個整數。在其函式定義中,我們定義了兩個基本情況:如果第二個引數為零,則返回1。如果第二個引數為1,則返回第一個引數(底數)。在其他情況下,函式返回一個遞迴呼叫,其引數為底數和(expo-1)乘以底數。即此函式返回底數的冪,直到expo的次數。在主函式中,我們宣告並初始化了底數和指數的變數,分別為base和expo,其值為2和5。我們使用這兩個變數作為引數呼叫了該函式,並使用print函式列印了返回的輸出。

結論

在本教程中,我們討論了在Haskell程式語言中實現計算數字冪的程式的四種不同方法。

更新於: 2022年12月14日

972 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.