java实现摄氏度和华氏度相互转换

公式说明

*华氏度转摄氏度 ℃ = (οF - 32) / 1.8 摄氏度转华氏度 °F = (9/5)*°C + 32

代码实践

import java.util.Scanner;

public class Convert {
          
   

	public static void main(String[] args) {
          
   
		/*
		 * 华氏度转摄氏度
		 * ℃ = (οF - 32) / 1.8
		 * 摄氏度转华氏度
		 * °F = (9/5)*°C + 32
		 * */
		double fahrenheit, degree;
		
		//华氏度转摄氏度
		System.out.print("输入华氏度:");
		Scanner doublefahrenheit = new Scanner(System.in);
		fahrenheit = doublefahrenheit.nextDouble();
		degree = (fahrenheit - 32)*5/9;
		
		//输出结果保留两位
		System.out.printf("对应的摄氏度是:%.2f℃
", degree);
		
		//摄氏度转华氏度
		System.out.print("输入摄氏度:");
		Scanner doubledegree = new Scanner(System.in);
		degree = doubledegree.nextDouble();
		fahrenheit = (9/5.0) * degree + 32;
		
		//输出结果保留两位
		System.out.printf("对应的华氏度是:%.2f℉
", fahrenheit);
				
		//释放内存
		doublefahrenheit.close();
		doubledegree.close();

	}

}

测试结果查看

经验分享 程序员 微信小程序 职场和发展