Devdit
 

not enough arguments in call to strconv.ParseFloat Go คือ วิธีแก้ไข

823

เขียนภาษา Go (Golang) รับตัวแปรจากผู้ใช้งาน และแปลงเป็นทศนิยม ลองรันแล้วขึ้น Error ว่า not enough arguments in call to strconv.ParseFloat อยากทราบว่าต้องแก้ไขอย่างไร

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

func main() {
	fmt.Print("Please input decimal : ")
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	f, _ := strconv.ParseFloat( scanner.Text() )
}

 

วิธีแก้ไข

การใช้คำสั่ง strconv.ParseFloat ต้องกำหนดค่าพารามิเตอร์ 2 ตัว คือ s string และ bitSize int จากโค้ดด้านบนมีการกำหนดค่าพารามิเตอร์แค่ตัวเดียว ไม่ได้กำหนด bitSize เช่น 32 หรือ 64 ให้แก้ไขโค้ดดังนี้

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

func main() {
	fmt.Print("Please input decimal : ")
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	f, _ := strconv.ParseFloat( scanner.Text(), 32 )
	fmt.Print( f )
}

ผลลัพธ์

Please input decimal : 33.56
33.560001373291016
แก้ไข 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ