英文:
Substrings and rounding in go
问题
package main
import (
"fmt"
"bufio"
"os"
"strconv"
)
func main() {
fmt.Print("加载中\n")
var xInp = bufio.NewScanner(os.Stdin)
var yInp = bufio.NewScanner(os.Stdin)
fmt.Print("请输入 y 的值:")
yInp.Scan()
fmt.Print("请输入 x 的值:")
xInp.Scan()
q, err := strconv.Atoi(yInp.Text())
w, err := strconv.Atoi(xInp.Text())
var slope = float64(q)/float64(w)
fmt.Printf("%.4f", slope)
fmt.Print(err)
}
我正在尝试使这段代码包含一个子字符串。当我输入 y 为 190,x 为 13 时,程序给出的答案是 14。但这是不正确的,它是一个无限小数。显然,我不想显示整个小数,但我想显示四位小数。例如,190/13 = 14.6153。如果你知道如何四舍五入小数,那可能更好。但两种方式都可以。
英文:
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)
}
I am trying to make this code have a substring. When I type in as y, 190. And x as 13. The answer, the program claims is 14. But that is not true. It is a infinite decimal. Obviously I do not want to show the whole decimal. But I do want to show 4 decimal places. for example 190/13 = 14.6153. It is also fine if you know how to round the decimal. That probably would be better. But both are fine.
答案1
得分: 1
根据我理解,您想要将两个数字相除并输出结果(与子字符串无关)。
问题在于您将整数除以整数,因此得到的结果也是整数。我在您的程序中主要做了以下更改:
var slope = float64(q)/float64(w) // 将两个整数转换为浮点数
fmt.Printf("%.4f\n", slope) // 将浮点数打印为四位小数
以下是修改后的代码:
package main
import (
"fmt"
"bufio"
"os"
"strconv"
)
func main() {
var xInp = bufio.NewScanner(os.Stdin)
var yInp = bufio.NewScanner(os.Stdin)
fmt.Print("请输入 y 值:")
yInp.Scan()
fmt.Print("请输入 x 值:")
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)
}
英文:
As far as I understood you want just two divide two numbers and output the result (it has nothing to do substrings).
The problem that you divide integer by integer and therefore gets back an integer. The main changes that I have done in your program are:
var slope = float64(q)/float64(w) // converted both ints to floats
fmt.Printf("%.4f\n", slope) // printed float to 4 decimal points
Basically here it is:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论