跳转到内容

编程基础/函数示例 Java

来自维基教科书,开放的书籍,为开放的世界
 // This program asks the user for a Fahrenheit temperature, 
 // converts the given temperature to Celsius,
 // and displays the results.
 //
 // References:
 // https://www.mathsisfun.com/temperature-conversion.html
 // https://wikibooks.cn/wiki/Java_Programming
 
 import java.util.*;
 
 class Main {
     private static Scanner input = new Scanner(System.in);
 
     public static void main(String[] args) {
         double fahrenheit;
         double celsius;
         
         fahrenheit = getFahrenheit();
         celsius = calculateCelsius(fahrenheit);
         displayResult(fahrenheit, celsius);
     }
 
     private static double getFahrenheit() {
         double fahrenheit;
         
         System.out.println("Enter Fahrenheit temperature:");
         fahrenheit = input.nextDouble();
         
         return fahrenheit;
     }
 
     private static double calculateCelsius(double fahrenheit) {
         double celsius;
         
         celsius = (fahrenheit - 32) * 5 / 9;
         
         return celsius;
     }
 
     private static void displayResult(double fahrenheit, double celsius) {
         System.out.println(fahrenheit + "° Fahrenheit is " + 
             celsius + "° Celsius");
     }
 }
Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

参考文献

[编辑 | 编辑源代码]
华夏公益教科书