You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 with parts := strings.Split(input, ","), then add parts[0] = strings.TrimSpace(parts[0]) and parts[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:44:31