首页 > 后端开发 > Golang > 正文

如何添加排除负数

PHPz
发布: 2024-02-09 23:30:09
转载
551 人浏览过

如何添加排除负数

php小编鱼仔为您介绍如何在编程中添加排除负数的方法。在某些情况下,我们需要对输入的数值进行限制,确保它们不会是负数。这在处理金钱、年龄等需要正数值的场景中尤为重要。通过使用条件语句和数学函数,我们可以轻松地实现这一目标。接下来,我们将详细讨论如何在不同编程语言中添加排除负数的方法,以帮助您解决这一常见问题。

问题内容

<code>
Write a program that queries the user for three positive integers and
displays messages:

All numbers are equal if all three numbers are equal

Two numbers are equal if any two numbers out of three are equal

All numbers are different if all three numbers entered are different


If there is an error in the input data, e.g., negative numbers are
entered, the program should display the message Invalid Input
</code>
登录后复制
package main

import (
    "fmt"
)

func main() {
    var a, b, c int
    fmt.Scan(&a)
    fmt.Scan(&b)
    fmt.Scan(&c)
    if (a != b && a > 0) && (b != c && c > 0) && (a != c && b > 0) {
        fmt.Print("All the numbers are different")
    } else if a == b && b == a && a == c && c == b {
        fmt.Print("All numbers are equal")
    } else if (a == b && b > 0) || (b == a && a > 0) || (c == a && a > 0) || (c == b && b > 0) {
        fmt.Print("Two numbers are equal")
    } else {
        fmt.Print("Invalid request")
    }
}
登录后复制

如果我输入例如 -4 -4 -4 如何使程序输出错误的查询?

解决方法

使用一套。在 Go 中实现集合的惯用方法是使用映射。

然后检查集合的长度。

package main

import (
    "fmt"
)

func main() {

    var a int = 5
    var b int = 9
    var c int = 5

    fmt.Scan(&a)
    fmt.Scan(&b)
    fmt.Scan(&c)

    s := map[int]bool{a: true, b: true, c: true}

    if a < 0 || b < 0 || c < 0 {
        fmt.Print("Invalid request")
    } else if len(s) == 3 {
        fmt.Print("All the numbers are different")
    } else if len(s) == 2 {
        fmt.Print("Two numbers are equal")
    } else if len(s) == 1 {
        fmt.Print("All numbers are equal")
    }

}
登录后复制

以上是如何添加排除负数的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!