左对齐输出

时间:2018-09-14 03:15:42

标签: string perl output

我正在做一个作业,在该作业中我必须对输出文本进行对齐。当我测试可能的程序时,我似乎无法使输出对齐。同样对于GPA,如果我试图证明文本的正确性,我会失去2个小数点的精度。这是我的代码

#Calculating $semester_gpa
if($credits_taken == 0) {
  exit();
}
my $total = $semester_gpa /= $credits_taken;

#Output formatting
printf ("The student name is: %-6s\n",$user_name);
printf ("Credits taken: %-6s\n", $credits_taken);
printf ("Credits passed: %-6s\n", $credits_passed);
printf ("GPA: %-6s %.2f\n", $total);

我的程序的输出如下 enter image description here

我到底在做什么错?

1 个答案:

答案 0 :(得分:1)

如果要使值左对齐,则无需使用printf,只需在标签字符串中添加空格即可。标签字符串是指"Credits taken: %s\n"(请注意:%之间的空格)

$user_name = 'Jogi';
$credits_taken = 13;
$credits_passed = 9;
$semester_gpa = 4.329;

#Calculating $semester_gpa
if($credits_taken == 0) {
  exit();
}
my $total = $semester_gpa /= $credits_taken;

#Output formatting
printf ("The student name is: %s\n", $user_name);
printf ("Credits taken:       %s\n", $credits_taken);
printf ("Credits passed:      %s\n", $credits_passed);
printf ("GPA:                 %.2f\n", $total);

即使您想右对齐,您仍应在标签字符串中放置空格,以使代码清晰易懂:

printf ("The student name is: %10s\n", $user_name);
printf ("Credits taken:       %10s\n", $credits_taken);
printf ("Credits passed:      %10s\n", $credits_passed);
printf ("GPA:                 %10.2f\n", $total);

请注意语法%10.2f将右对齐与十进制精度结合在一起。

要使对齐字段的宽度动态,可以使用特殊的*(星号)syntax for printf

$width = 20;
printf ("The student name is: %*s\n", $width, $user_name);
printf ("Credits taken:       %*s\n", $width, $credits_taken);
printf ("Credits passed:      %*s\n", $width, $credits_passed);
printf ("GPA:                 %*.2f\n", $width, $total);

如果需要,您甚至可以使精度动态化:

$width = 20;
$precision = 2;
printf ("GPA:                 %*.*f\n", $width, $precision, $total);