将两个值相除得到0
问题描述:
I'm trying to make a division of two variables, but when I want to print the result, the program prints out 0
the leadTime and endAmount are being correctly printed by te program, but the monthlyAmount is being printed as 0. Also if I remove the float64() around endAmount and leadTime it is being printed as 0
var leadTime int
if currentAge < 45 {
leadTime = 120
} else if currentAge > 45 && currentAge < 55 {
leadTime = 90
} else if currentAge > 55 {
leadTime = 60
}
endAmount, _ := strconv.Atoi(amountAsString)
monthlyAmount:= (float64(endAmount) / float64(leadTime)
fmt.Println("leadTime :", leadTime )
fmt.Println("Total amount:", endAmount)
fmt.Println("monthlyAmount:", monthlyAmount)
with the standardinput I'm testing with, the leadTime = 120 and the endAmount = 93735.00 so the monthlyAmount should be: 781.13
答
The problem is your trying to convert floating string an int in
endAmount, _ := strconv.Atoi(amountAsString)
This will give an error, but you're just neglecting it. Use strconv.ParseFloat(amountAsString, 64)
to solve your problem.
Check the playground example to see the error and the working code