卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

golang 负数和正数

golang 负数和正数

php小编子墨在这里为大家介绍一下关于golang中负数和正数的知识。在golang中,负数和正数是用不同的表示方式来表示的。负数使用补码表示,而正数则直接使用二进制表示。这一点在进行数值计算时尤为重要,因为负数和正数的运算方式是不同的。了解这些细节将帮助开发者更好地理解和处理数字运算,提高代码的效率和可靠性。

问题内容

我不知道如何正确构建代码。请帮帮我吧(

这是任务本身

编写一个程序,使用输入的数字来确定应将其放入四个堆栈中的哪一个。该程序要求用户输入数字并显示一条消息:

1.数字为负数,即使该数字小于零并且是偶数

2.如果数字小于零且为奇数,则该数字为负奇数

3.数字是正数,即使该数字大于零并且是偶数

4.如果数字大于零且为奇数,则该数字为正奇数

我尝试了 if 和 else

另外我不明白是否可以使用 - 开关执行?

已经很头疼了。我唯一能做的就是定义整数和非整数。我不明白要在代码中添加什么来定义负数和正数。

package main

import (
    "fmt"
)

func main() {
    var score int
    fmt.Scanln(&score)
    if score%2 == 0 && score < 0 {
        fmt.Println("The number is negative and even")
    } else {
        fmt.Println("The number is negative and not even")
    }
}

为什么输入正数时,程序仍然写出该数是负数

因为我指定了a<0

请帮助我

解决方法

您的程序会将您输入的所有数字分类为“负”,因为您的程序中没有打印“正”一词的打印语句。

您可以使用不同但仍然相当简单的方法来解决此问题:

package main

import "fmt"

func main() {
    var score int
    _, err := fmt.Scanln(&score)
    if err != nil {
        panic(err)
    }

    // print whether the number is negative, zero, or positive, and also whether it is even or odd, in one line
    // take note that fmt.Print is used here and not Println, so that it does not append a newline to the end of the string
    if score < 0 {
        fmt.Print("The number is negative")
    } else if score == 0 {
        fmt.Print("The number is zero")
    } else {
        fmt.Print("The number is positive")
    }

    if score%2 == 0 {
        fmt.Println(" and even")
    } else {
        fmt.Println(" and odd")
    }
}
卓越飞翔博客
上一篇: go LoadDLL 其依赖项不在 System 或 System32 中
下一篇: 如何使用 Twitter API v2 使用 Go 发布推文?
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏