Q:

Rust program to read a float number from the user

belongs to collection: Rust Basic Programs

0

Here, we will read a floating-point number from the user and print the input value.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to read an integer number from the user is given below. The given program is compiled and executed successfully.

// Rust program to read a float number 
// from the user

use std::io;

fn main() {
    let mut num:f32=0.0;
    let mut input = String::new();
    
    println!("Enter number: ");
    io::stdin().read_line(&mut input).expect("Not a valid string");
    num = input.trim().parse().expect("Not a valid number");
    
    println!("Number is: {}",num);
}

Output:

RUN 1:
Enter number: 
123.45
Number is: 123.45

RUN 2:
Enter number: 
Hello
thread 'main' panicked at 
'Not a valid number: ParseFloatError { kind: Invalid }', 
src/libcore/result.rs:1084:5
note: run with `RUST_BACKTRACE=1` environment variable 
to display a backtrace.

Explanation:

Here, we created a 32-bit floating-point variable num and then read the value for num from the user using the read_line() function and printed the result.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to print the ASCII value of a charact... >>
<< Rust program to read an integer number from the us...