golang:为什么我得到+ Inf而不是整数或浮点数?

时间:2012-12-06 08:37:23

标签: go

我正在学习golang,正在研究货币计算的时间价值

我正在尝试计算一段时间来说,加倍你的钱。我使用的公式是period = log(fv/pv) / log(1 + i)。到目前为止我所拥有的是......

package main
import (
    "fmt"
    "math"
)
var (
    interest,
    futureValue,
    period,
    presentValue float64
)
var rate float64 = interest / 100 //converts interest into decimal... interest / 100
var ratex float64 = 1 + interest //used for (1 + i)

func main() {
    numPeriod()
}
func numPeriod() {
    fmt.Println("Enter interest amount: ")
    fmt.Scanf("%g", &interest)
    fmt.Println("Enter present value: ")
    fmt.Scanf("%g", &presentValue)
    fmt.Println("Enter future value: ")
    fmt.Scanf("%g", &futureValue)
    var logfvpvFactor float64 = futureValue / presentValue
    var logi float64 = math.Log(ratex)
    var logfvpv float64 = math.Log(logfvpvFactor)
    period = logfvpv / logi
    fmt.Printf("Number of period/s is = %g\n", period)
}

运行这个,我得到......

Number of period/s is = +Inf

...我正在寻找的答案是整数或浮点数。我怎么做到的?

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

为了扩展迭戈的答案,你有一句话

var ratex float64 = 1 + interest
在定义兴趣之前

,因此它是0并且ratex变为1.然后你有行

var logi float64 = math.Log(ratex)

并且由于ratex为1,并且1的日志为0,因此logi变为0.然后通过除以logi定义周期,即0,因此您将获得+ inf。

您应该做的是在获得感兴趣的输入后将值分配给ratex。

答案 1 :(得分:2)

当您指定ratex的值时,interest为0.因此,增加值所需的时间将为无穷大。你想要的是:

func numPeriod() {
  fmt.Println("Enter interest amount: ")
    fmt.Scanf("%g", &interest)
    var ratex float64 = 1 + interest / 100 //used for (1 + i)
    fmt.Println("Enter present value: ")
    fmt.Scanf("%g", &presentValue)
    fmt.Println("Enter future value: ")
    fmt.Scanf("%g", &futureValue)
    var logfvpvFactor float64 = futureValue / presentValue
    var logi float64 = math.Log(ratex)
    var logfvpv float64 = math.Log(logfvpvFactor)
    period = logfvpv / logi
    fmt.Printf("Number of period/s is = %g\n", period)
}

答案 2 :(得分:1)

(09:54) jnml@fsc-r550:~/src/tmp/SO/13739751$ cat main.go 
package main

import (
        "fmt"
        "math"
)

func main() {
        var i, pv, fv float64
        fmt.Println("Enter interest amount: ")
        fmt.Scanf("%g", &i)
        fmt.Println("Enter present value: ")
        fmt.Scanf("%g", &pv)
        fmt.Println("Enter future value: ")
        fmt.Scanf("%g", &fv)
        fmt.Printf("Number of period/s is = %g\n", math.Log(fv/pv)/math.Log(1+i))
}

(09:54) jnml@fsc-r550:~/src/tmp/SO/13739751$ go run main.go 
Enter interest amount: 
.1
Enter present value: 
100
Enter future value: 
200
Number of period/s is = 7.272540897341713
(09:54) jnml@fsc-r550:~/src/tmp/SO/13739751$