0

我根本没有 Java 经验,并且正在使用文本编辑器编写代码,所以我看不出问题是什么(我从命令行运行)我看到错误并且知道它是什么但我不知道如何要解决这个问题

System.out.print(String.format("%7d", Math.pow(n,2).toString()));

我也试过没有.toString() 基本上,如果我只打印 n 它可以工作,但是 power 函数给我一个错误可能是因为返回类型,但是 pow 应该返回一个 double 并且字符串格式 %7d 可能也是 double 对吗?

4

5 回答 5

3

您使用了错误的格式说明符..%d用于整数。

Math.pow()返回double不能调用toString()方法的原语。

尝试使用%7swhich is for String,并将您的原始双精度值转换为Wrapper type: -

String.format("%7s", Double.valueOf(Math.pow(n,2)).toString())

但是,您不需要将参数转换为String,您可以直接使用double valuewith %f:-

String.format("%.3f", Math.pow(n,2));
于 2012-10-14T18:31:29.367 回答
1

您很可能希望使用f而不是d不使用toString. 如果您确实能够做到toString(正如 Quoi 指出的那样,您不能从原语中做到),那么将无法使用Formatters 期望使用的Number对象(Double在您的情况下)。

这是Formatter使用的String.format

于 2012-10-14T18:33:54.877 回答
0

双精度的正确格式是 %f 而不是 %d 所以修改你的代码:

 System.out.print(String.format("%7f",  Math.pow(n,2)));

另见:链接

于 2012-10-14T18:44:06.510 回答
0

问题在于toString方法。您已经给出了格式说明符%7d,这意味着integer. 您不能打印字符串来代替它。

于 2012-10-14T18:35:48.167 回答
0

Math#pow(double,double)返回原始双精度值,您不能调用toString方法。使用 f 代替 d,d 表示十进制整数。

 System.out.format("%7f", Math.pow(n,2));

最好从 Eclipse 或任何其他编辑器开始编写代码。

于 2012-10-14T18:33:49.520 回答