如何将输出列表,以便计算与摄氏和华氏相符?
另外,如何更自然地显示183.20000000000002
这样的数字?
public static void main(String[] args) {
double cel = 0;
double fahrenheit =cel * 1.8+ 32;
int i;
System.out.println();// blank line
System.out.print("Hello ");// output line
System.out.println();
System.out.println("This Program will show temperature conversions from 0-100\nThen in reverse \nCelsius Fahrenheit");
for (i = 0; i <25; i++){
cel =cel+ 4;
fahrenheit =cel * 1.8+ 32;
System.out.println(+ cel + " " + fahrenheit);
}
}
答案 0 :(得分:1)
您可以使用String#format
或System.out.printf
生成格式化输出,例如
public static void main(String[] args) {
double cel = 0;
double fahrenheit = cel * 1.8 + 32;
int i;
System.out.println();// blank line
System.out.print("Hello ");// output line
System.out.println();
System.out.println("This Program will show temperature conversions from 0-100\nThen in reverse");
System.out.printf("%s | %s%n", "Celsius", "Fahrenheit");
for (i = 0; i < 25; i++) {
cel = cel + 4;
fahrenheit = cel * 1.8 + 32;
System.out.printf(" %6.2f | %6.2f%n", cel, fahrenheit);
}
}
哪些输出......
Hello
This Program will show temperature conversions from 0-100
Then in reverse
Celsius | Fahrenheit
4.00 | 39.20
8.00 | 46.40
12.00 | 53.60
16.00 | 60.80
20.00 | 68.00
24.00 | 75.20
28.00 | 82.40
32.00 | 89.60
36.00 | 96.80
40.00 | 104.00
44.00 | 111.20
48.00 | 118.40
52.00 | 125.60
56.00 | 132.80
60.00 | 140.00
64.00 | 147.20
68.00 | 154.40
72.00 | 161.60
76.00 | 168.80
80.00 | 176.00
84.00 | 183.20
88.00 | 190.40
92.00 | 197.60
96.00 | 204.80
100.00 | 212.00
查看this以了解有关可用格式选项的更多详情
答案 1 :(得分:0)
使用DecimalFormat类确保只显示正确的小数位数。 Floating Points(包括双精度,只是&#34;双宽&#34;浮点)使用特殊的二进制表示,一些小数不总是正确舍入。使用格式化类可确保您不输出比用户预期更长的数字(例如告诉用户价格为1.0000001美元并不是一个好习惯 - 这也是浮点数差的部分原因选择钱等事情。
示例:
double data = 0.08d+0.02d;
//The # means "optional digit", the zeros mean mandatory
//e.g. 4 formatted with "#.##" would be "4", but with
//"#.00" would be "4.00"
DecimalFormat fmt = new DecimalFormat("#.00");
System.out.println(fmt.format(data));
要解决问题的第二部分(尽管这应该是一个单独的问题),我建议您查看printf()
。 Here是使用它的好指南。