Programming Fundamentals/Function Examples JavaScript

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Temperature[edit | edit source]

 // 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://en.wikibooks.org/wiki/JavaScript
 
 main();
 
 function main() {
   var fahrenheit = getFahrenheit();
   var celsius = calculateCelsius(fahrenheit);
   displayResult(fahrenheit, celsius);
 }
 
 function getFahrenheit() {
   var fahrenheit = input("Enter Fahrenheit temperature:");
   return fahrenheit;
 }
 
 function calculateCelsius(fahrenheit) {
   var celsius = (fahrenheit - 32) * 5 / 9;
   return celsius;
 }
 
 function displayResult(fahrenheit, celsius) {
   output(fahrenheit + "° Fahrenheit is " + 
     celsius + "° Celsius");
 }
 
 function input(text) {
   if (typeof window === 'object') {
     return prompt(text)
   }
   else if (typeof console === 'object') {
     const rls = require('readline-sync');
     var value = rls.question(text);
     return value;
   }
   else {
     output(text);
     var isr = new java.io.InputStreamReader(java.lang.System.in); 
     var br = new java.io.BufferedReader(isr); 
     var line = br.readLine();
     return line.trim();
   }
 }
 
 function output(text) {
   if (typeof document === 'object') {
     document.write(text);
   } 
   else if (typeof console === 'object') {
     console.log(text);
   } 
   else {
     print(text);
   }
 }

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

References[edit | edit source]