2

这是代码部分:

    System.out.println("The values of pi from term " + (userNum - 9) + " to term " + userNum + " are:");        
        for (int x = 1; x < userNum; x++) 
            {
                if (x % 2 == 1)
                    sum = sum + (4.0/(2 * x - 1));
                else
                    sum = sum - (4.0/(2 * x - 1));
            System.out.println("Term " + (x) + ": " + sum);
            }

这是输出:

The values of pi from term 2 to term 11 are:
Term 1: 4.0
Term 2: 2.666666666666667
Term 3: 3.466666666666667
Term 4: 2.8952380952380956
Term 5: 3.3396825396825403
Term 6: 2.9760461760461765
Term 7: 3.2837384837384844
Term 8: 3.017071817071818
Term 9: 3.2523659347188767
Term 10: 3.0418396189294032

第 10 学期的小数点需要与其他小数点对齐。在 Java 中如何做到这一点?谢谢。

4

3 回答 3

3
于 2012-07-13T02:09:32.730 回答
1

如果您使用Apache commons lang,您可以使用StringUtils该类来完成您所需要的:

System.out.println("Term " + 
    StringUtils.leftPad("" + x, (userNum.length() - x.length()), ' ')
      + ": " + sum);
于 2012-07-13T02:08:08.967 回答
0

Term根据 的位数,您似乎想添加空格x

    int j = String.valueOf(x).length();
    String sp = "";
    while( j++ < String.valueOf(userNum).length() )
        sp += " ";
    System.out.printf("Term %s %d : %.15f\n", sp, x, sum);
于 2012-07-13T02:12:46.433 回答