Go语言:如何修改readFloat函数以读取两个float64类型数值
Alright, let's tackle this input splitting issue you're facing. The goal is to modify your existing function to read two floating-point numbers from a single input line, right? Here's a straightforward solution that handles common input cases and error scenarios:
Modified Function to Read Two Floats
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func readTwoFloats() (float64, float64) { scanner := bufio.NewScanner(os.Stdin) for { scanner.Scan() input := scanner.Text() // Split input by any whitespace (works for spaces, tabs, etc.) // For comma-separated input, use strings.Split(input, ",") instead parts := strings.Fields(input) if len(parts) != 2 { fmt.Println("ERROR: Please enter exactly two numbers separated by space(s)") fmt.Print("\nTry again: ") continue } x, errX := strconv.ParseFloat(parts[0], 64) y, errY := strconv.ParseFloat(parts[1], 64) if errX != nil { fmt.Printf("ERROR: Invalid number for first value - %v\n", errX) fmt.Print("\nTry again: ") continue } if errY != nil { fmt.Printf("ERROR: Invalid number for second value - %v\n", errY) fmt.Print("\nTry again: ") continue } // All checks passed, return the two floats return x, y } } func main() { fmt.Print("\nEnter x, y coordinates for point1: ") x1, y1 := readTwoFloats() fmt.Printf("You entered point1: (%.2f, %.2f)\n", x1, y1) }
Key Details Explained
Flexible Input Splitting:
strings.Fields(input)splits the input using any whitespace (spaces, tabs, etc.), which is user-friendly for most cases.- If you need to support comma-separated values (like
3.14,2.71), replace that line withparts := strings.Split(input, ","), then addparts[0] = strings.TrimSpace(parts[0])andparts[1] = strings.TrimSpace(parts[1])to clean up extra spaces around the comma.
Clear Error Handling: The function first checks if the input splits into exactly two parts, then validates each number individually. This gives users specific feedback on what went wrong (e.g., invalid first number vs. missing second value).
Loop Until Valid: Just like your original function, it keeps prompting the user until they provide valid input.
内容的提问来源于stack exchange,提问作者r_duck
相关产品推荐
相关产品推荐

