在将华氏温度转换为摄氏温度的Java程序中,DecimalFormat无法正常工作

时间:2017-04-15 18:09:42

标签: java

第一次在这里发帖。我在使用需要使用DecimalFormat的程序时遇到问题。我是Java大学生的简介,我们的任务是:

让用户以华氏温度输入温度,将程序转换为摄氏温度,打印出原始温度和转换,使用单循环将华氏温度每次增加10度并打印出20次增量的转换,并使用DecimalFormat为2个小数位格式化摄氏度。

到目前为止,我一切正常,但输出没有显示我设置的DecimalFormat。它只输出摄氏34,45,87等。它从不输出小数位。如果我将DecimalFormat更改为#.00,则打印出34.00,45.00等。我将非常感谢您的帮助。到目前为止,这是我的代码。

import java.text.DecimalFormat;
import java.util.Scanner;

public class TempConvert {

    public static void main(String[] args) {

        /**
         * Formats celsius to two decimal places.
         */
        DecimalFormat f = new DecimalFormat("##.##");

        /**
         * Declare the variables
         */
        int fahrenheitTemp, count = 0;
        double celsiusTemp;

        /**
         * User inputs temperature.
         */
        Scanner scan = new Scanner(System.in);

        /**
         * Ask user to input a temperature in Fahrenheit.
         */

        System.out.print("Enter a temperature in Fahrenheit between -459 and 212: ");
        fahrenheitTemp = scan.nextInt();

        /**
         * Check to see if temperature is within parameters.
         */
        while (fahrenheitTemp <= -459 || fahrenheitTemp >= 212) {
            System.out.print("Temperature entered is out of Range. Please try again: ");
            fahrenheitTemp = scan.nextInt();
        }

        /**
         * Convert input to celsius.
         */

        celsiusTemp = ((fahrenheitTemp - 32) * 5) / 9;

        /**
         * Loop to add +10 degrees to fahrenheit and print out for 20 cycles.
         */
        while (count < 20) {

            fahrenheitTemp += 10;
            celsiusTemp = ((fahrenheitTemp - 32) * 5) / 9;

            System.out.print("Temperatute in Fahrenheit: " + fahrenheitTemp);
            System.out.println("\tCelsius: " + f.format(celsiusTemp));

            count++;
        }
    }

}

0 个答案:

没有答案