Golang 如何检查数字是正数还是负数
在本教程中,我们将学习如何检查数字是正数还是负数。本教程包括两种方法,一种是使用math库中的内置函数Signbit()来实现。另一种方法是使用关系运算符对数字与零进行比较,并预测数字是否为正数。
方法1:使用Signbit()函数
在这个示例中,我们将使用math库中的内置函数Signbit()来检查数字是正数还是负数。
语法
Signbit()是一个在math库中接受一个浮点类型参数的函数,如下所示。
func Signbit(f float64)
步骤
- 步骤 1 - 初始化浮点数。
-
步骤 2 - 在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.
方法2:使用关系运算符
在这个示例中,我们将使用关系运算符>=和<来检查一个数是正数还是负数。
语法
这个方法使用关系运算符<和>=,具体语法如下。
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的知识,你可以探索这些教程。
极客笔记