如何在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.