在Golang中,`printf()`, `sprintf()`, 和 `fprintf()` 是三个用于格式化输出的函数,它们在用法和功能上有一些区别。 1. `fmt.Printf()`: 这个函数用于将格式化的字符串输出到标准输出(通常是终端)。它的用法是 `fmt.Printf(format, args...)`,其中 `format` 是一个格式化字符串,`args` 是要格式化的参数列表。例如: ```go package main import "fmt" func main() { name := "Alice" age := 30 fmt.Printf("My name is %s and I'm %d years old.\n", name, age) } ``` 输出:`My name is Alice and I'm 30 years old.` 2. `fmt.Sprintf()`: 这个函数用于将格式化的字符串输出到一个字符串变量中。它的用法是 `string = fmt.Sprintf(format, args...)`,其中 `format` 是一个格式化字符串,`args` 是要格式化的参数列表。例如: ```go package main import "fmt" func main() { name := "Alice" age := 30 message := fmt.Sprintf("My name is %s and I'm %d years old.", name, age) fmt.Println(message) } ``` 输出:`My name is Alice and I'm 30 years old.` 3. `fmt.Fprintf()`: 这个函数用于将格式化的字符串输出到文件中。它的用法是 `file.Write(fmt.Fprintf(file, format, args...))`,其中 `file` 是一个文件对象,`format` 是一个格式化字符串,`args` 是要格式化的参数列表。例如: ```go package main import ( "fmt" "os" ) func main() { name := "Alice" age := 30 file, _ := os.Create("output.txt") file.Write(fmt.Fprintf(file, "My name is %s and I'm %d years old.\n", name, age)) file.Close() } ``` 在这个例子中,输出的字符串被写入到一个名为 "output.txt" 的文件中。 [2023-11-09 18:13:21 | AI问答 | 523点数解答]