如何在Go語言中檢查數字是正數還是負數?


在本教程中,我們將學習如何檢查數字是正數還是負數。本教程包括兩種方法,一種是使用math庫中內建的Signbit()函式;另一種是使用關係運算符,透過將數字與零比較來判斷數字是正數還是負數。

方法一:使用Signbit()函式

在這個例子中,我們將使用math庫中內建的Signbit()函式來檢查數字是正數還是負數。

語法

Signbit()是math庫中的一個函式,它接受一個float型別的引數,如下所示。

func Signbit(f float64)

演算法

  • 步驟1 − 初始化浮點數。

  • 步驟2 − 開始if條件,並在if條件中呼叫Signbit()函式。

  • 步驟3 − 據此列印結果。

示例

package main
import (

   // fmt package provides the function to print anything
   "fmt"
   
   // Math library is providing Signbit() function
   "math"
)
func main() {

   // declaring and initializing the variable using the shorthand method in Golang
   number := -20.0
   fmt.Println("Golang program to check whether the number is positive or not using Signbit() function in the Math library.")
   
   // calling the Signbit() function and running the if else block accordingly
   if math.Signbit(number) {
      fmt.Printf("The number %f is negative.\n", number)
   } else {
      fmt.Printf("The number %f is positve.\n", number)
   }
}

輸出

Golang program to check whether the number is positive or not using Signbit() function in the Math library.
The number -20.000000 is negative.

方法二:使用關係運算符

在這個例子中,我們將使用關係運算符>=和<來檢查數字是正數還是負數。

語法

此方法使用關係運算符<,>=,語法如下。

if number < 0 {}
If number >= 0 {}

演算法

  • 步驟1 − 初始化浮點數。

  • 步驟2 − 使用相應的關係運算符比較數字。

  • 步驟3 − 據此列印結果。

示例

package main
import (

   // fmt package provides the function to print anything
   "fmt"
)
func main() {

   // declaring and initializing the variable using the shorthand method in Golang
   number := 10.0
   fmt.Println("Golang program to check that the number is positive or not using the relational operators.")
   fmt.Println("Checking whether the number is positive or not using the > operator.")
   
   // using the > operator and running the if else block accordingly
   if number < 0 {
      fmt.Printf("The number %f is negative.\n", number)
   } else {
      fmt.Printf("The number %f is positve.\n", number)
   }
   fmt.Println("Checking whether the number is positive or not using the >= operator.")
   
   // using the >= operator and running the if else block accordingly
   if number >= 0 {
      fmt.Printf("The number %f is positve.\n", number)
   } else {
      fmt.Printf("The number %f is negative.\n", number)
   }
}

輸出

Golang program to check that the number is positive or not using the relational operators.
Checking whether the number is positive or not using the > operator.
The number 10.000000 is positve.
Checking whether the number is positive or not using the >= operator.
The number 10.000000 is positve.

結論

這是檢查數字是否為正數的兩種方法。第一種方法在模組化和程式碼可重用性方面更適用。要了解更多關於Go語言的知識,您可以瀏覽這些教程。

更新於:2023年1月11日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.