【问题标题】:Pascal's Triangle output alignment帕斯卡三角输出对齐
【发布时间】:2018-03-22 12:12:51
【问题描述】:

所以我想出了三角形本身的值的代码。我目前正在努力的是如何对齐/居中打印的值。我尝试了很多东西,但现在我可以使用一些帮助。如果有人知道如何做到这一点,请随时分享!谢谢

Program Tri_pas;
Uses Crt;
Var
    linha,ordem,a,b: byte;  


Function fat(X: byte): real; // factorial
Var fat1:  real;
Begin

  fat1:=1;  
  If X <= 1 Then  
    fat:=1
  Else
  Begin
    Repeat
      fat1:=(fat1 * X);
      X:=(X - 1);
    Until X <= 1;
    fat:=fat1;
  End;

End;



Procedure nCp(n,p: byte);  //Combinations
Var
    i: byte;
    nCp: real;
Begin

  If n < 1 Then
    n:=0  
  Else
    n:=(n-1);

  For i:=0 to n do    
  Begin
    writeln;
    For p:=0 to i do  
    Begin
      nCp:= fat(i) / (fat(p) * fat(i - p));    //  mathematic formula for the combinations      
      Write(nCp:1:0,' ');
    End;
  End;

End;


{ Main Programa  }

Begin

  Write('Insert a line(1 -> n) :  ');
  Readln(linha);
  nCp(linha,ordem);
  readln;  

End.

【问题讨论】:

    标签: alignment output pascal pascals-triangle


    【解决方案1】:

    只需在字符串前添加适当数量的空格即可。请注意,我使用了双空格,并将占位符大小更改为 4 (3+1) 以更好地格式化。

    For p := 1 to (n - i) do
      Write('  ');
    
    For p:=0 to i do
    Begin
      nCp:= fat(i) / (fat(p) * fat(i - p));    //  mathematic formula for the combinations
      Write(nCp:3:0,' ');
    End;
    

    附:在没有实数的合理范围内,有更有效的方法来计算 Ncr。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2012-07-13
      • 1970-01-01
      • 2012-10-24
      相关资源
      最近更新 更多