1 回答
TA贡献1842条经验 获得超12个赞
打印值时,它使用默认表示法。从 fmt 文档中:
The default format for %v is:
...
float32, complex64, etc: %g
...
The default precision for ... %g it is the smallest number of digits necessary
to identify the value uniquely.
下面修改了您的代码以演示这一点:
package main
import (
"fmt"
"os"
"bufio"
"strconv"
)
func main() {
var d float64 = 4.0
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Printf("Enter a number: ")
scanner.Scan()
b, err := strconv.ParseFloat(scanner.Text(), 64)
if err != nil {
fmt.Println(err)
continue
}
result := b + d
fmt.Println("\nResult:")
fmt.Printf("\t%%v: %v\n", result)
fmt.Printf("\t%%g: %g\n", result)
fmt.Printf("\t%%f: %f\n\n", result)
}
}
$ go run test.go
Enter a number: 5
Result:
%v: 9
%g: 9
%f: 9.000000
Enter a number: 5.5
Result:
%v: 9.5
%g: 9.5
%f: 9.500000
Enter a number: 7.8910
Result:
%v: 11.891
%g: 11.891
%f: 11.891000
Enter a number:
- 1 回答
- 0 关注
- 67 浏览
添加回答
举报