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

Golang fmt.Printf如何实现右侧补0生成指定格式数字金字塔

Go 实现右侧补0金字塔结构的解决方案

%0-*d 不生效的原因:
Go 标准库 fmt 包的格式化规则中,0 填充标志仅在右对齐时生效,搭配左对齐标志 - 使用时,0 标志会被默认忽略,仅能填充空格,因此无法直接通过格式化符实现右侧补0的效果。

下面给出两种可直接运行的实现方案:

方案1:字符串拼接实现(逻辑直观易理解)

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	inputs := []int{1, 3, 4, 5, 6, 7, 9}
	totalLength := len(inputs)
	for idx, num := range inputs {
		numStr := strconv.Itoa(num)
		// 计算需要补的0的数量
		padZeroCount := totalLength - idx - len(numStr)
		result := numStr + strings.Repeat("0", padZeroCount)
		fmt.Println(result)
	}
}

方案2:算术运算实现(无需额外依赖包)

通过给原数字乘以对应数量的10的幂次,直接得到末尾带0的结果:

package main

import "fmt"

func main() {
	inputs := []int{1, 3, 4, 5, 6, 7, 9}
	totalLength := len(inputs)
	for idx, num := range inputs {
		multiplier := 1
		// 需要补几个0就乘几次10
		for i := 0; i < totalLength - idx -1; i++ {
			multiplier *= 10
		}
		fmt.Println(num * multiplier)
	}
}

两种方案运行后均可得到你期望的输出:

1000000
300000
40000
5000
600
70
9

内容的提问来源于stack exchange,提问作者Chun Chun Maru

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 06:36:10