打印格式错误

printf format error

由于 "illegal format conversion exception",我的值不会打印出来。我想知道如何解决这个问题。

这是我的代码:

double n = 0;
System.out.printf("%10d", n);

使用 %f 作为浮点值,而不是 %d,后者仅适用于整数。

因此您的原始代码可能如下所示:

public static void main(String... args) {
    System.out.printf("%-10s %10s %n", "Term", "Value");

    double pi = 0;

    for (int i = 1, div = 1; i <= 20; i++, div += 2)
        System.out.printf("%-10d %10f\n", i, pi = i % 2 == 0 ? pi - 4. / div : pi + 4. / div);
}

"%d" 用于整数类型。对浮点值使用 "%f"

double n = 0.0d;
System.out.printf("%10f", n);

有关字符串格式化程序规则的详细信息,请查看 its official documentation