Rust Program: Adding two numbers
Rust Basic: Exercise-2 with Solution
Write a Rust program that accepts two numbers from the user, adds them together, and displays the result.
Sample Solution:
Rust Code:
use std::io;
fn main() {
println!("Enter the first number:");
let mut input1 = String::new();
io::stdin().read_line(&mut input1).expect("Failed to read input.");
let num1: f64 = input1.trim().parse().expect("Please enter a valid number.");
println!("Enter the second number:");
let mut input2 = String::new();
io::stdin().read_line(&mut input2).expect("Failed to read input.");
let num2: f64 = input2.trim().parse().expect("Please enter a valid number.");
let sum = num1 + num2;
println!("The sum of {} and {} is: {}", num1, num2, sum);
}
Output:
The sum of 10 and 22 is: 32
Explanation:
Here's a brief explanation of the above Rust code:
- Import the "io" module from the standard library to handle user input.
- Inside the "main()" function, we prompt the user to enter the first number.
- Create a mutable String variable 'input1' to store the user's input. We use io::stdin().read_line(&mut input1) to read the input from the user.
- Parse 'input1' into a floating-point number (f64) using the "trim()" method to remove leading and trailing whitespace, and "parse()" to convert the string to a number. We use "expect()" to handle errors during parsing.
- Repeat the same process for the second number.
- Calculate the sum of 'num1' and 'num2' and store it in the variable 'sum'.
- Finally, we print the sum using println!().
Rust Code Editor:
Previous: Rust System information gathering program.
Next: Rust Program: Variable counter operations.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/rust/basic/rust-basic-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics