Rust Function: Celsius to Fahrenheit conversion
Write a Rust function to convert a temperature value from Celsius to Fahrenheit.
Sample Solution:
Rust Code:
// Define a function named 'celsius_to_fahrenheit' that takes a temperature in Celsius as input and returns the temperature in Fahrenheit
fn celsius_to_fahrenheit(celsius: f64) -> f64 {
// Convert Celsius to Fahrenheit using the formula: (Celsius * 9/5) + 32
(celsius * 9.0 / 5.0) + 32.0
}
fn main() {
let celsius_temperature = 25.0; // Define the temperature in Celsius
// Call the 'celsius_to_fahrenheit' function with the specified Celsius temperature
let fahrenheit_temperature = celsius_to_fahrenheit(celsius_temperature);
// Print the converted temperature in Fahrenheit
println!("Temperature in Celsius: {}°C", celsius_temperature);
println!("Temperature in Fahrenheit: {}°F", fahrenheit_temperature);
}
Output:
Temperature in Celsius: 25°C Temperature in Fahrenheit: 77°F
Explanation:
Here's a brief explanation of the above Rust code:
- 'fn celsius_to_fahrenheit(celsius: f64) -> f64 { ... }': This is a function named 'celsius_to_fahrenheit' that takes a temperature in Celsius as input (of type 'f64', a 64-bit floating-point number) and returns the equivalent temperature in Fahrenheit (also of type 'f64').
- Inside the function:
- We convert the temperature from Celsius to Fahrenheit using the formula: '(Celsius * 9/5) + 32'.
- In the 'main' function:
- Define the temperature in Celsius ('celsius_temperature').
- Call the 'celsius_to_fahrenheit' function with the specified Celsius temperature and store the result in 'fahrenheit_temperature'.
- Finally we print both the original temperature in Celsius and the converted temperature in Fahrenheit.
Rust Code Editor:
Previous: Rust Program: Calculate nth Fibonacci number.
Next: Rust Program: Print Fibonacci Sequence up to Specified Terms.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics