w3resource

Rust Program: Cube Root of user input

Rust Handling Errors with Result and Option: Exercise-1 with Solution

Write a Rust program that reads an integer from user input and prints its cube root, handling invalid input.

Sample Solution:

Rust Code:

use std::io;

fn main() {
    println!("Enter an integer to find its cube root:"); // Prompt the user to enter an integer

    let mut input = String::new(); // Create a mutable String to store user input

    io::stdin().read_line(&mut input).expect("Failed to read line"); // Read user input from stdin

    let trimmed_input = input.trim(); // Remove leading/trailing whitespaces and newlines

    match trimmed_input.parse::() {
        // Try to parse the trimmed input string into an i32
        Ok(num) => {
            // If parsing is successful, calculate the cube root and print the result
            let cube_root = (num as f64).cbrt();
            println!("Cube root of {} is {:.2}", num, cube_root);
        }
        Err(_) => {
            // If parsing fails, print an error message
            eprintln!("Invalid input: Please enter a valid integer");
        }
    }
}

Output:

Enter an integer to find its cube root:
Cube root of 125 is 5.00

Explanation:

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

  • The program prompts the user to enter an integer.
  • It reads user input from standard input (stdin) and stores it in a mutable "String" named 'input'.
  • The "trim()" method removes leading and trailing whitespaces and new lines from the input.
  • The parse::<i32>() method attempts to parse the trimmed input string into an 'i32'. If successful, the parsed number is stored in the 'num' variable.
  • Inside the 'match' block, if parsing is successful (Ok(num)), the program calculates the cube root of the parsed number using the "cbrt()" method from the 'f64' type (since "cbrt()" is not directly available for 'i32').
  • If parsing fails (Err(_)), the program prints an error message indicating invalid input.

Rust Code Editor:

Previous: Rust Handling Errors with Result and Option Exercises.
Next: Rust Function: Read file with Error handling.

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.