How can I tabulate my output so that the calculations line up with Celsius and Fahrenheit?
Also, how do I display a number like 183.20000000000002
more naturally?
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);
}
}
You can use either String#format
or System.out.printf
to generate formatted output, for example
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);
}
}
Which outputs...
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
Check out this for more details about the available formatting options
Use the DecimalFormat class to ensure that only the right number of decimals show up. Floating Points (including doubles, which are just "double wide" floating points) use a special binary representation and some decimals don't always round correctly. Using Formatting classes ensures that you don't output a number that is longer than a user expected (eg telling a user a price is $1.0000001 wouldn't be good practice--its part of the reason why floating points are poor choices for things like money).
Example:
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));
To address the second part of your question (although that should be in a separate question altogether), I recommend you review printf()
. Here is a good guide on its use.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.