gpt4 book ai didi

java - 在 Java 中与 printf 左对齐

转载 作者:搜寻专家 更新时间:2023-10-30 21:02:24 25 4
gpt4 key购买 nike

当我运行程序时,阶乘值右对齐。有没有办法在保持中间 50 个空格的同时使其左对齐?

public class Exercise_5_13
{
public static void main( String[] args )
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20 };

long factorial = 0;

try
{
System.out.print("\n\n");
System.out.printf("%s%50s\n", "Integer", "factorial");

for ( int number : numbers )
{
System.out.printf( "%4d", number);
factorial = (long)1;

for(int i=1; i <= number; i++)
factorial = factorial * (long)i;

System.out.printf("%50.0f\n",(double)factorial);
}

System.out.print("\n\n");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

最佳答案

根据 printf() 规范,- 符号左对齐输出。

System.out.printf("%-50.0f\n",(double)factorial);

来源: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

关于java - 在 Java 中与 printf 左对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15075899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com