这是我的代码:

public class TemperatureConverter {
public static float convertTemp1 (float temperature,
    char convertTo) {
    return convertTo;}
    public static String convertTemp (float temperature, char convertTo) {

     if (convertTo=='F'){
     return "The temperature in Fahrenheit is " + (9*temperature/5 + 32);
    } else if(convertTo=='C') {
     return "The temperature in Celsius is " + (temperature - 32) * 5/9;
    }  else{
     return "You can enter either F or C as convertTo argument";

}
}

public static void main(String[] args) {

System.out.println("Converting 21C to Fahrenheit. " +  convertTemp(21,'F', 0));
System.out.println("Converting 70F to Celsius. " + convertTemp(70,'C', 0));
}
}


这是运行时的输出:

将21C转换为华氏度。华氏温度是69.8

将70F转换为摄氏。摄氏温度是21.11111

我一直在尝试,一次又一次地将tje 2.11111更改为2.11,小数点后仅2位数字。可以有人帮我得到这个:

将21C转换为华氏度。华氏温度是69.8

将70F转换为摄氏。摄氏温度是21.11111

对此:

将21C转换为华氏度。华氏温度是69.8

将70F转换为摄氏。摄氏温度是21.11

最佳答案

您可以使用String.format()指定小数点后应显示多少位数:

class Main {
  public static String convertTemp (float temperature, char convertTo) {
    if (convertTo == 'F') {
      return String.format("The temperature in Fahrenheit is %.1f", (9*temperature/5 + 32));
    } else if (convertTo == 'C') {
      return String.format("The temperature in Celsius is %.2f", (temperature - 32) * 5/9);
    } else {
      return "You can enter either F or C as convertTo argument";
    }
  }

  public static void main(String[] args) {
    System.out.println("Converting 21C to Fahrenheit. " +  convertTemp(21,'F'));
    System.out.println("Converting 70F to Celsius. " + convertTemp(70,'C'));
  }
}


输出:

Converting 21C to Fahrenheit. The temperature in Fahrenheit is 69.8
Converting 70F to Celsius. The temperature in Celsius is 21.11


试试吧here!

10-04 19:17