6

我正在学习 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

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

谢谢你的帮助!

4

3 回答 3

6

为了扩展迭戈的答案,你有这条线

var ratex float64 = 1 + interest

在定义利息之前,它是 0,ratex 变为 1。然后你有这条线

var logi float64 = math.Log(ratex)

由于 ratex 为 1,而 1 的 log 为 0,logi 变为 0。然后您通过除以 logi(即 0)来定义周期,因此您将得到 +inf。

您应该做的是在获得利息的输入后将值分配给 ratex 。

于 2012-12-06T14:56:00.957 回答
2

当您分配 ratex 的值时,利息为 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)
}
于 2012-12-06T08:51:10.103 回答
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$ 
于 2012-12-06T08:58:23.360 回答