【问题标题】:Spacing error in the output of the program程序输出中的间距错误
【发布时间】:2019-10-21 22:10:15
【问题描述】:

"编写一个程序,打印一个包含 (ln n)、n、n *(ln n)、n2、n3 和 2n,用于 n = 16、32、64、...、2048。使用制表符('\t' 字符)排列列。"

这是任务。但是,在使用 \t 时,输出的间距不正确。值之间的间距不均匀,一些值向右移动。我该如何解决这个问题?

public class Main {
  public static void main(String[] args) { 

      for (int n = 16; n<2049; n*=2){
          System.out.println(Math.log(n) +"\t"+ n + "\t"+ (Math.log(n)*n)+"\t"+Math.pow(n,2)+"\t"+Math.pow(n,3)+"\t"+Math.pow(2,n)+"\t");
      }
  }
}

【问题讨论】:

    标签: java tabs spacing


    【解决方案1】:

    好的,制表符很好,但请记住,它们可能被标记为 8 个空格,而当我运行这段代码时,它会将你的双打打印到比这更多的数字。链接的答案解释了如何将您的数字格式化为更少的位置。

    Related Stack Overflow Question

    我个人会使用带有格式字符串的 System.out.printf。

    您可以使用此格式字符串。请注意,我添加了空格以提高可读性——您最终会希望在满意后将其删除。

    public class Main {
      public static void main(String[] args) {
    
          for (int n = 16; n<2049; n*=2){
              //System.out.println(Math.log(n) +"\t"+ n + "\t"+ (Math.log(n)*n)+"\t"+Math.pow(n,2)+"\t"+Math.pow(n,3)+"\t"+Math.pow(2,n)+"\t");
              System.out.printf( "%12.5f\t %6d\t %12.5f\t %14.0f\t %14.0f\t %16.0f\n",
                  Math.log(n), n,
                  Math.log(n)*n,
                  Math.pow(n,2),
                  Math.pow(n,3),
                  Math.pow(2,n));
          }
      }
    }
    

    这并不完美,因为最后一列变得非常大非常快。但我最终得到这样的输出:

     2.77259         16      44.36142               256            4096             65536
     3.46574         32     110.90355              1024           32768        4294967296
     4.15888         64     266.16852              4096          262144  18446744073709552000
     4.85203        128     621.05987             16384         2097152  340282366920938460000000000000000000000
     5.54518        256    1419.56543             65536        16777216  115792089237316200000000000000000000000000000000000000000000000000000000000000
     6.23832        512    3194.02221            262144       134217728  13407807929942597000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
     6.93147       1024    7097.82713           1048576      1073741824          Infinity
     7.62462       2048   15615.21968           4194304      8589934592          Infinity
    

    【讨论】:

    • 谢谢!我最初打算使用 System.out.printf 但这个问题专门要求标签,所以我不确定。这行得通!
    【解决方案2】:

    做这样的事情:

    System.out.print(format(n) + "\t");
    System.out.print(format(Math.log(n)) + "\t");
    System.out.print(format(Math.log(n)*n) + "\t");
    

    并定义一个函数“format”,它返回一个字符串并在前面加上 n-input.length 个空格,以便每个输入的长度相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      相关资源
      最近更新 更多