gpt4 book ai didi

go - Float64 类型打印为 Golang 中的 int

转载 作者:IT王子 更新时间:2023-10-29 02:28:15 25 4
gpt4 key购买 nike

令人惊讶的是,我找不到其他人遇到同样的问题;我尝试简单地在 Go 中初始化一个 float64 并打印它,然后尝试进行字符串转换并打印它。两种输出都不准确。

我已经用很多分数尝试过这个,包括那些不解析为重复小数的分数,以及简单地写出 float 和打印(例如 num := 1.5 然后 fmt.Println(num) 给出输出 1)。

package main

import (
"fmt"
"strconv"
)

func main() {
var num float64
num = 5/3
fmt.Printf("%v\n", num)
numString := strconv.FormatFloat(num, 'f', -1, 64)
fmt.Println(numString)
}

预期:

// Output:
1.66
1.66

实际:

// Output:
1
1

最佳答案

The Go Programming Language Specification

Integer literals

An integer literal is a sequence of digits representing an integer constant.

Floating-point literals

A floating-point literal is a decimal representation of a floating-point constant. It has an integer part, a decimal point, a fractional part, and an exponent part. The integer and fractional part comprise decimal digits; the exponent part is an e or E followed by an optionally signed decimal exponent. One of the integer part or the fractional part may be elided; one of the decimal point or the exponent may be elided.

Arithmetic operators

For two integer values x and y, the integer quotient q = x / y and remainder r = x % y satisfy the following relationships:

x = q*y + r  and  |r| < |y|

with x / y truncated towards zero.


您使用整数文字和算术(x/y 截断为零)写道:

package main

import (
"fmt"
"strconv"
)

func main() {
var num float64
num = 5 / 3 // float64(int(5)/int(3))
fmt.Printf("%v\n", num)
numString := strconv.FormatFloat(num, 'f', -1, 64)
fmt.Println(numString)
}

Playground :https://play.golang.org/p/PBqSbpHvuSL

输出:

1
1

您应该使用浮点文字和算术来编写:

package main

import (
"fmt"
"strconv"
)

func main() {
var num float64
num = 5.0 / 3.0 // float64(float64(5.0) / float64 (3.0))
fmt.Printf("%v\n", num)
numString := strconv.FormatFloat(num, 'f', -1, 64)
fmt.Println(numString)
}

Playground :https://play.golang.org/p/Hp1nac358HK

输出:

1.6666666666666667
1.6666666666666667

关于go - Float64 类型打印为 Golang 中的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57031651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com