3.14: JavaScript Examples
- Page ID
- 10633
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)
Temperature
// 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 celisus = calculateCelsius(fahrenheit); displayResult(fahrenheit, celisus); } function getFahrenheit() { var fahrenheit = input("Enter Fahrenheit temperature:"); return fahrenheit; } function calculateCelsius(fahrenheit) { var celisus = (fahrenheit - 32) * 5 / 9; return celisus; } function displayResult(fahrenheit, celisus) { output(fahrenheit + "° Fahrenheit is " + celisus + "° Celsius"); } // Checks the JavaScript environment and reads from the console, // the current document, or standard input as appropriate. function input(text) { if (typeof console === "object") { return prompt(text); } 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(); } } // Checks the JavaScript environment and writes to the console, // the current document, or standard output as appropriate. // Reference: http://progopedia.com/example/hello-world/114/ function output(text) { if (typeof console === "object") { console.log(text); } else if (typeof document === "object") { document.write(text); } else { print(text); } }
Output
Enter Fahrenheit temperature: 100 100° Fahrenheit is 37.7777777777778° Celsius
References
- Wikiversity: Computer Programming