dongqiu7365 2015-12-01 20:35
浏览 315

为什么浮点数和整数= Nan? 在去

package main

import (
    "fmt"
    "math"
)

func main() {
    // x= +- sqrtB-4ac/2a
    cal()
}

func cal() {
    b := 3
    a := 4
    c := 2
    b2 := float64(b*b)
    ac := float64(4)*float64(a)*float64(c)
    q := math.Sqrt(b2-ac)
    fmt.Print(q)
}

This will output a NaN, but why. I am trying to make a quadratic calculator. All I want is for this to output the number.

  • 写回答

3条回答 默认 最新

  • dop20345 2015-12-01 20:36
    关注

    Because you're trying to take the square root of a negative number which isn't a valid operation (not just in Go, in math) and so it returns NaN which is an acronym for Not A Number.

    b := 3
    a := 4
    c := 2
    b2 := float64(b*b) // sets b2 == 9
    ac := float64(4)*float64(a)*float64(c) // ac == 32 
    q := math.Sqrt(b2-ac) // Sqrt(9-32) == Sqrt(-23) == NaN
    fmt.Print(q)
    q = math.Sqrt(math.Abs(b2-ac)) // suggested in comments does Sqrt(23) == ~4.79 
    // perhaps the outcome you're looking for.
    

    EDIT: please don't argue semantics on the math bit. If you want to discuss square roots of negative numbers this isn't the place. Generally speaking, it is not possible to take the square root of a negative number.

    评论

报告相同问题?