Java Printf不适用于双精度数组
我对printf有问题。我想打印出两个sepreate双精度数组,并将小数点限制为一位,但我得到了一个错误。 第一个数组将以摄氏度为单位打印温度,第二个数组将获取这些值并将其更改为Farenheit,该值也将打印到屏幕上。我试图在打印出数字时实现printf方法。我能想到的唯一问题是,我引用的是数组中的索引值,而不是实际的双精度值Java Printf不适用于双精度数组,java,arrays,printf,Java,Arrays,Printf,我对printf有问题。我想打印出两个sepreate双精度数组,并将小数点限制为一位,但我得到了一个错误。 第一个数组将以摄氏度为单位打印温度,第二个数组将获取这些值并将其更改为Farenheit,该值也将打印到屏幕上。我试图在打印出数字时实现printf方法。我能想到的唯一问题是,我引用的是数组中的索引值,而不是实际的双精度值 import java.util.Scanner; public class tempOne { public static void main (Strin
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.
}
}
}
有人知道这里发生了什么吗?删除+”
打印文件末尾的
%.1f
表示“打印一个小数点后的浮点值”,但使用+”
将该数字转换为字符串删除+”
末尾的+”
%.1f
表示“打印一个小数点后的浮点值”,但使用+”
将该数字转换为字符串您希望设置双精度格式,并传递字符串参数。尝试(删除+“”
):
您希望设置双精度格式,并传递字符串参数。尝试(删除+“”
):
@如果这对你有帮助的话,请不要随意接受这个答案out@Scoot如果这对你有帮助的话,请随意接受这个答案
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)
System.out.printf("Temperatures in Farenheit: %.1f", temp2[index])