Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 打印至温度小数点后一位的格式_Java_Formatting_Decimal - Fatal编程技术网

Java 打印至温度小数点后一位的格式

Java 打印至温度小数点后一位的格式,java,formatting,decimal,Java,Formatting,Decimal,我对Java非常陌生,我必须编写一个程序,从-40华氏度到120华氏度,然后将其转换为摄氏度,然后以5的增量在两列中显示,精确到小数点后一位。我已经完成了大部分代码,我有正确的华氏温度输出,但我不知道如何让摄氏度精确到小数点后一位。一切都会有帮助的 package 3; public class prog2 { public static void main(String[] args) { System.out.println("Fahrenheit to Ce

我对Java非常陌生,我必须编写一个程序,从-40华氏度到120华氏度,然后将其转换为摄氏度,然后以5的增量在两列中显示,精确到小数点后一位。我已经完成了大部分代码,我有正确的华氏温度输出,但我不知道如何让摄氏度精确到小数点后一位。一切都会有帮助的

package 3;

public class prog2 {

     public static void main(String[] args) {
         System.out.println("Fahrenheit to Celsius converter from -40F below to 120F");
          for(double temp = -40.0; temp <= 120; temp += 5) 
          {
             System.out.printf("%10.1f", temp);
             double sum = (temp -32) * (5.0/9.0);  
             System.out.printf("%5d",(int) sum );
             System.out.println();          
      }
   }

}
package 3;
公共类程序2{
公共静态void main(字符串[]args){
System.out.println(“华氏温度到摄氏温度从-40F到120F的转换器”);

对于(双温度=-40.0;温度将总和的打印更改为:

System.out.printf(“%10.1f”,总和);


格式设置与第一列相同,并且不将计算值强制转换为int。

您可以通过向构造函数发送格式设置字符串来使用DecimalFormat类。在您的示例中,“#”表示一位数字,“.”表示小数点。 查看此链接了解更多信息

你可以这样做:

public static void main(String[] args) {
    System.out.println("Fahrenheit to Celsius converter from -40F below to 120F");
    DecimalFormat df = new DecimalFormat("###.#");
    for (double temp = -40.0; temp <= 120; temp += 5) {
        System.out.printf("%sC°", df.format(temp));
        double sum = (temp - 32) * (5.0 / 9.0);
        System.out.printf("= %sF°", df.format(sum));
        System.out.println();
    }
}
publicstaticvoidmain(字符串[]args){
System.out.println(“华氏温度到摄氏温度从-40F到120F的转换器”);
DecimalFormat df=新的DecimalFormat(“###.#”);

对于(double temp=-40.0;temp
System.out.printf(“%10.1f”,temp);
…似乎正朝着正确的方向移动。也许您应该在这两个值之间打印一个空格。您还可以将所有3个打印语句组合成一个:
System.out.printf(“%10.1f%5d%n”,temp,(int)((temp-32)*5/9))
这就是我在阅读你的评论之前所做的……谢谢!