【问题标题】:How do I organize the output of this code? [duplicate]如何组织此代码的输出? [复制]
【发布时间】:2013-08-12 01:55:03
【问题描述】:

这个程序的输出是一个表格,但是有点乱。如何对齐不同的列?谢谢

代码:

import math   

for a in range(1, 10):
    x = 3.0
    while True:
        y = (x + a/x) / 2
        if y == x:
            break
        x = y  
    sq = math.sqrt(a)
print float(a), sq, x, abs(sq - x)

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    使用str.format:

    import math   
    
    for a in range(1, 10):
        x = 3.0
        while True:
            y = (x + a/x) / 2
            if y == x:
                break
            x = y  
        sq = math.sqrt(a)
        print '{:>5} {:>5.10f} {:>5.10f} {:>5.10f}'.format(float(a), sq, x, abs(sq - x))
    

    打印

      1.0 1.0000000000 1.0000000000 0.0000000000
      2.0 1.4142135624 1.4142135624 0.0000000000
      3.0 1.7320508076 1.7320508076 0.0000000000
      4.0 2.0000000000 2.0000000000 0.0000000000
      5.0 2.2360679775 2.2360679775 0.0000000000
      6.0 2.4494897428 2.4494897428 0.0000000000
      7.0 2.6457513111 2.6457513111 0.0000000000
      8.0 2.8284271247 2.8284271247 0.0000000000
      9.0 3.0000000000 3.0000000000 0.0000000000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-08
      • 2015-07-29
      • 1970-01-01
      • 2011-03-16
      • 2016-09-28
      • 1970-01-01
      • 2016-11-13
      • 2017-06-27
      相关资源
      最近更新 更多