w3resource

Rust: Calculate circumference from diameter and PI

Rust Variables and Data Types: Exercise-2 with Solution

Write a Rust function that calculates the circumference of a circle using the constant PI and a given diameter.

Sample Solution:

Rust Code:

const PI: f64 = 3.14159; // Define the constant PI

// Define a function named 'calculate_circumference' that takes a diameter as input and returns the circumference
fn calculate_circumference(diameter: f64) -> f64 {
    let radius = diameter / 2.0; // Calculate the radius of the circle
    let circumference = 2.0 * PI * radius; // Calculate the circumference using the formula: C = 2 * π * r
    circumference // Return the calculated circumference
}

fn main() {
    let diameter = 10.0; // Define the diameter of the circle
    let circumference = calculate_circumference(diameter); // Call the 'calculate_circumference' function
    println!("The circumference of the circle with diameter {} is {:.2}", diameter, circumference); // Print the result
}

Output:

The circumference of the circle with diameter 10 is 31.42

Explanation:

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

  • const PI: f64 = 3.14159;: This line defines a constant named 'PI' with a value of π (approximately 3.14159). The 'f64' type annotation specifies that the constant is of type 'f64' (64-bit floating-point number).
  • fn calculate_circumference(diameter: f64) -> f64 { ... }: This is a function named "calculate_circumference()" that takes a 'diameter' (as a 'f64' floating-point number) as input and returns the circumference of the circle (also as a 'f64' floating-point number).
  • let radius = diameter / 2.0;: This line calculates the radius of the circle by dividing the diameter by 2.
  • let circumference = 2.0 PI radius;: This line calculates the circumference of the circle using the formula: C = 2 π r, where 'C' is the circumference, 'π' is the constant PI, and r is the radius of the circle.
  • circumference: This line returns the calculated circumference as the result of the function.
  • fn main() { ... }: This is the entry point of the program.
  • let diameter = 10.0;: This line defines the diameter of the circle. You can change this value to calculate the circumference for a different circle.
  • let circumference = calculate_circumference(diameter);: This line calls the calculate_circumference function with the specified diameter and stores the result in the 'circumference' variable.
  • println!("The circumference of the circle with diameter {} is {:.2}", diameter, circumference);: This line prints the result, showing the diameter and the calculated circumference with two decimal places.

Rust Code Editor:

Previous: Rust Age Calculator: Calculate Age based on birth year and current year.
Next: Rust: Increment counter by specified amount.

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.