gpt4 book ai didi

perl - 在 Perl 中使用 'printf' 格式化输出

转载 作者:行者123 更新时间:2023-12-05 04:18:37 24 4
gpt4 key购买 nike

我正在尝试格式化我的输出,使其看起来像在列中。我正在尝试使用 printf功能。

这是我所拥有的:

printf("%s %10s %12s %10s\n", "Qty", "Desc.", "Unit \$", "Total");

for ($he = 0; $he <= 6; $he++) {
if (@quantity[$he] != 0) {
printf("%d %10s %12.2f %10.2f\n", @quantity[$he], @selections[$he], @prices[$he], @prices[$he] * @quantity[$he])
}
}

我正在努力使 for 循环的 if 语句中的第二个 printf 与“Qty”、“Desc”对齐。 、“单位\$”和“总计”。

最佳答案

您需要在两种格式中使用相同的数字:

printf("%3s %10s %15s %13s\n", "Qty", "Desc.", "Unit \$", "Total");

printf("%3d %10s %12.2f %10.2f\n", @quantity[$he], @selections[$he], @prices[$he], @prices[$he]*@quantity[$he])

注意12.2的意思是(12位+1点+2位),这就是为什么我在第一种格式中写了15。 13 也是如此。


另请注意,您访问的数组元素不正确。

使用 $quantity[$he] 代替 @quantity[$he]。也就是说,将 @ 替换为 $

关于perl - 在 Perl 中使用 'printf' 格式化输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13038611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com