c printf(%* s)说明

时间:2016-09-23 19:08:18

标签: c printf

所以,我试图输出马里奥金字塔的格式化字符串,即:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)    Handles Button1.Click


    Dim but As Integer
    If sender.text = "" Then


        but = Mid(sender.name.ToString, 7, Len(sender.name.ToString) - 6)

        i = Int(but / 9)
        j = but Mod 9 - 1
        If j < 0 Then
            i = i - 1
            j = 8
        End If
        If m(i, j) = 0 Then
            sender.visible = False
        Else
            If m(i, j) = -1 Then
                MsgBox("you lose")
            Else
                sender.text = m(i, j)
            End If
        End If

    End If
End Sub

圆点代表空格。高度由用户在运行时确定。以下代码是我发现的工作原理。

   ##
  ###
 ####

现在你看到了什么有效,让我们看看一些不起作用的东西,除了for循环外,一切都是一样的。

#include <stdio.h>

void hash(void) {
  printf("%s", "#");
}

int main(void) {
  int height;
  printf("%s", "Enter height of mario's pyramid: ";
  scanf("%i", &height);

  for (int i = 0; i < height; i++) {
    int spaces;
    if (height == 1 || i == (height - 1) {
      spaces = 0;
    }
    else {
      spaces = height - (i + 1);
      printf("%*s", spaces, " ");
    }
    for (int j = 0; j < (i + 1); j++) {
      hash();
    }
    printf("\n");
  }

  return 0;
}

因此,正如您所看到的,唯一的区别是条件语句,如果#include <stdio.h> void hash(void) { printf("%s", "#"); } int main(void) { int height; printf("%s", "Enter height of mario's pyramid: "; scanf("%i", &height); for (int i = 0; i < height; i++) { int spaces; spaces = height - (i + 1); printf("%*s", spaces, " "); for (int j = 0; j < (i + 1); j++) { hash(); } printf("\n"); } return 0; } height == 1将空格设置为0,但结果完全不同。出于某种原因,当使用条件语句时,空间似乎不打印,这实际上是我想要的,但我很确定这不是我应该怎么做。所以,我想知道是否有人知道这里到底发生了什么,并可以向我解释。

2 个答案:

答案 0 :(得分:2)

此命令:

printf("%*s", spaces, " ");

将始终至少打印一个空格,因为单个空格是您要打印的字符串。

更改它以打印空字符串:

printf("%*s", spaces, "");

答案 1 :(得分:1)

for循环的最后一次迭代中,spaces的值为0,这相当于

printf("%*s", 0, " ");
即使宽度说明符为printf

0也会打印空格,更改为:

if (spaces > 0)
    printf("%*s", spaces, " ");