w3resource

Rust Program: Convert Celsius to Fahrenheit

Rust Variables and Data Types: Exercise-5 with Solution

Write a Rust program that creates an integer variable temp and assign it a temperature value in Celsius. Convert it to Fahrenheit and print the result.

Sample Solution:

Rust Code:

fn main() {
    // Declare an integer variable 'temp' to store the temperature in Celsius
    let temp_celsius: i32 = 20;

    // Convert the temperature from Celsius to Fahrenheit
    let temp_fahrenheit: f64 = celsius_to_fahrenheit(temp_celsius);

    // Print the result
    println!("Temperature in Celsius: {:.2}°C", temp_celsius);
    println!("Temperature in Fahrenheit: {:.2}°F", temp_fahrenheit);
}

// Define a function to convert temperature from Celsius to Fahrenheit
fn celsius_to_fahrenheit(celsius: i32) -> f64 {
    // Calculate the temperature in Fahrenheit using the formula: F = (C * 9/5) + 32
    let fahrenheit = (celsius as f64 * 9.0 / 5.0) + 32.0;
    fahrenheit // Return the temperature in Fahrenheit
}

Output:

Temperature in Celsius: 20°C
Temperature in Fahrenheit: 68.00°F

Explanation:

Here's a brief explanation of the above Rust code:

  • 'fn main() { ... }': This is the program's entry point.
  • 'let temp_celsius: i32 = 20;': This line declares an integer variable named 'temp_celsius' and initializes it with the value '20', representing the temperature in Celsius.
  • 'let temp_fahrenheit: f64 = celsius_to_fahrenheit(temp_celsius);': This line calls the 'celsius_to_fahrenheit' function to convert the temperature from Celsius to Fahrenheit and stores the result in the variable 'temp_fahrenheit'.
  • 'println!("Temperature in Fahrenheit: {:.2}°F", temp_fahrenheit);': This line prints the converted temperature in Fahrenheit with two decimal places.
  • 'fn celsius_to_fahrenheit(celsius: i32) -> f64 { ... }': This is a function named 'celsius_to_fahrenheit' that takes a temperature in Celsius as input and returns the corresponding temperature in Fahrenheit as a floating-point number ('f64').
  • 'let fahrenheit = (celsius as f64 9.0 / 5.0) + 32.0;': This line calculates the temperature in Fahrenheit using the formula '(C 9/5) + 32', where 'C' is the temperature in Celsius. The result is stored in the variable 'fahrenheit'.

Rust Code Editor:

Previous: Rust Weather Condition Checker: Check and set Boolean variable for Sunny weather.
Next: Rust Greeting Program: Print Welcome Message with Your Name.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.