0

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

代码:

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)
4

1 回答 1

2

使用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
于 2013-08-10T03:54:28.630 回答