在Go语言中,可以使用main包来测试一个变量是否为自然数吗?

huangapple go评论70阅读模式
英文:

Is there a way to test if a variable in Go is a natural number using only the main package?

问题

我正在尝试检测变量y是否为自然数,而不使用额外的包。这种可能吗?例如,我想在EXPRESSION下面打印一条消息,如果它是非自然数,但不知道该放什么。有没有简单的解决方案?谢谢。

package main
import "fmt"

var y = -2.3

func main() {
  if (EXPRESSION){
    fmt.Println("非自然数!")
  }
}
英文:

I am trying to detect if a variable y is a natural number without resorting to extra packages. Is this possible? For example, I am trying to print a message if it is a non-natural number but do not know what to put in EXPRESSION below. Is there a simple solution for this? Thanks.

package main
import "fmt"

var y = -2.3

func main() {
  if (EXPRESSION){
    fmt.Println("non-natural number!")
  }
}

答案1

得分: 1

如@voker所提到的,y <= 0 || float64(int(y)) != y应该可以完成任务。

英文:

as @voker mentions, y &lt;= 0 || float64(int(y)) != y should do the job.

答案2

得分: 1

以下条件应该可以正常工作:

1. y * -1 >= 0
2. y <= 0
英文:

Following condition should work fine


 1. y * -1 &gt;= 0 
 2. y &lt;= 0

huangapple
  • 本文由 发表于 2021年8月31日 13:41:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/68993412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定