Programming Fundamentals/Functions/Rust
functions.rs
edit// This program asks the user for a Fahrenheit temperature,
// converts the given temperature to Celsius,
// and displays the results.
//
// References:
// https://www.geeksforgeeks.org/standard-i-o-in-rust/
// https://www.includehelp.com/rust/read-a-float-number-from-the-user.aspx
// https://doc.rust-lang.org/book/ch03-03-how-functions-work.html
use std::io;
fn main() {
let fahrenheit = get_fahrenheit();
let celsius = calculate_celsius(fahrenheit);
display_result(fahrenheit, celsius);
}
fn get_fahrenheit() -> f32 {
println!("Enter Fahrenheit temperature:");
let mut line = String::new();
io::stdin().read_line(&mut line).expect("Error reading line");
let fahrenheit:f32 = line.trim().parse().expect("Not a valid number");
return fahrenheit;
}
fn calculate_celsius(fahrenheit:f32) -> f32 {
let celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
return celsius;
}
fn display_result(fahrenheit:f32, celsius:f32) {
println!("{}° Fahrenheit is {}° Celsius", fahrenheit, celsius);
}
Try It
editCopy and paste the code above into one of the following free online development environments or use your own Rust compiler / interpreter / IDE.