首頁  >  文章  >  後端開發  >  如何新增排除負數

如何新增排除負數

PHPz
PHPz轉載
2024-02-09 23:30:09543瀏覽

如何新增排除負數

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刪除