【问题标题】:Printf not working for array of doublesPrintf 不适用于双精度数组
【发布时间】:2015-12-02 21:25:38
【问题描述】:

我遇到了 printf 的问题。我想打印出两个单独的双精度数组并将小数位限制为一位,但出现错误。 第一个数组将打印摄氏温度,第二个数组将获取这些值并将它们更改为华氏温度,该值也将打印到屏幕上。当数字被打印出来时,我正在尝试实现 printf 方法。我能想到的唯一问题是我引用的是数组中的索引值,而不是实际上的双精度值。

import java.util.Scanner;
public class tempOne {
    public static void main (String [] args){
        Scanner sc = new Scanner(System.in);
        double [] temp1 = new double [10];
        double [] temp2 = new double[10];
        System.out.println("Please enter 10 temperatures in Celsius: ");

        for (int index = 0; index<temp1.length;index++)//Gets temperatures in Celsius.
        {
            temp1[index]=sc.nextDouble();
        }

        for (int index = 0; index<temp1.length;index++)//Prints temperatures in Celsius.
        {
            System.out.printf("Temperatures in Celsius: %.1f", temp1[index] + " ");
        }

        for (int index = 0; index<temp1.length;index++)//Copies array 1 into array 2.
        {
            temp2[index]=temp1[index];
        }

        System.out.println("");

        for (int index = 0; index<temp1.length;index++)//Changes values in array 2 to Farenheit.
        {
            temp2[index] = ((temp1[index]*9/5)+32);
        }

        for (int index = 0; index<temp1.length;index++)
        {
            System.out.printf("Temperatures in Farenheit: %.1f", temp2[index] + " ");//Prints array 2.
        }

    }
}

结果如下:

Please enter 10 temperatures in Celsius: 
20.22
Temperatures in Celsius: Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
    at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2806)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2753)
    at java.util.Formatter.format(Formatter.java:2520)
    at java.io.PrintStream.format(PrintStream.java:970)
    at java.io.PrintStream.printf(PrintStream.java:871)
    at tempOne.main(tempOne.java:16)

有人知道这里发生了什么吗?

【问题讨论】:

    标签: java arrays printf


    【解决方案1】:

    删除printfs 末尾的+ " "

    %.1f 的意思是“打印一个小数点后一位的浮点值”,但使用 + " ",您将该数字转换为 String

    【讨论】:

    • @Scoot 如果对您有所帮助,请随时接受这个作为答案
    【解决方案2】:

    您想格式化双精度并改为传递字符串参数。试试(去掉+ ""):

    System.out.printf("Temperatures in Farenheit: %.1f", temp2[index])
    

    【讨论】:

      猜你喜欢
      • 2014-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      相关资源
      最近更新 更多