gpt4 book ai didi

go - go 中的子字符串和舍入

转载 作者:数据小太阳 更新时间:2023-10-29 03:41:25 26 4
gpt4 key购买 nike

package main

import (
"fmt"
"bufio"
"os"
"strconv"
)

func main() {
fmt.Print("loaded\n")
var xInp = bufio.NewScanner(os.Stdin)
var yInp = bufio.NewScanner(os.Stdin)

fmt.Print("insert y value: ")
yInp.Scan()
fmt.Print("Insert x value: ")
xInp.Scan()

q, err := strconv.Atoi(yInp.Text())
w, err := strconv.Atoi(xInp.Text())

var slope = q/w
fmt.Print(slope)
fmt.Print(err)
}

我试图让这段代码有一个子字符串。当我输入 y 时,190。x 为 13。程序声称答案是 14。但事实并非如此。是无限小数。显然我不想显示整个小数点。但我确实想显示小数点后 4 位。例如 190/13 = 14.6153。如果您知道如何舍入小数点也很好。那可能会更好。但两者都很好。

最佳答案

据我了解,您只需要两个除以两个数字并输出结果(它与子字符串无关)。

将整数除以整数并因此得到整数的问题。我在您的程序中所做的主要更改是:

var slope = float64(q)/float64(w)  // converted both ints to floats
fmt.Printf("%.4f\n", slope) // printed float to 4 decimal points

基本上是这样的:

package main

import (
"fmt"
"bufio"
"os"
"strconv"
)

func main() {
var xInp = bufio.NewScanner(os.Stdin)
var yInp = bufio.NewScanner(os.Stdin)
fmt.Print("insert y value: ")
yInp.Scan()
fmt.Print("Insert x value: ")
xInp.Scan()
q, err := strconv.Atoi(yInp.Text())
w, err := strconv.Atoi(xInp.Text())
var slope = float64(q)/float64(w)
fmt.Printf("%.4f\n", slope)
fmt.Println(err)
}

关于go - go 中的子字符串和舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34010650/

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