package main
import "fmt"
func main() {
fmt.Printf("My weight on the surface of Mars is %v lbs,", 149.0*0.3783)
fmt.Printf(" and I would be %v years old.n", 41*365/687)
fmt.Printf("My weight on the surface of %v is %v lbs.n", "Earth", 149.0)
fmt.Printf("%-15v $%4vn", "SpaceX", 94)
fmt.Printf("%-15v $%4vn", "Virgin Galactic", 100)
}
输出结果
My weight on the surface of Mars is 56.3667 lbs, and I would be 21 years old. My weight on the surface of Earth is 149 lbs. SpaceX $ 94 Virgin Galactic $ 100 Process finished with the exit code 0
与print和println不一样的是,printf接受的第一个参数总是文本,第二个参数则是表达式,而文本中包含的格式化变量%v则会在之后被替换成表示式的值
printf和print如果要将输出内容推进至下一行,需要放置换行符n
printf除可以在任意位置将格式化变量替换成指定的值以外,还能调整文本的对齐位置,如%4v将文本的宽度填充至4个字符,当宽度为正时,空格将被填充至文本左边,为负时将填充至文本右边
注:格式化变量的宽度指定了打印整个实数(包括整数部分、小数部分和小数点在内)



