Home »
Rust »
Rust Programs
Rust program to calculate the power of a given number
Input the number (n) and power (p), find the power of the given number i.e., n to the power p (np) using Rust program.
Submitted by Nidhi, on September 26, 2021
Problem Solution:
Here, we will read the number and power from the user. Then we will calculate the power of a given number using the pow() function and print the result.
Program/Source Code:
The source code to calculate the power of a given number is given below. The given program is compiled and executed successfully.
// Rust program to calculate the
// power of given number
use std::io;
fn main() {
let mut n:u32 = 0;
let mut p:u32 = 0;
let mut res:u32 = 0;
let mut input1 = String::new();
let mut input2 = String::new();
println!("Enter number: ");
io::stdin().read_line(&mut input1).expect("Not a valid string");
n = input1.trim().parse().expect("Not a valid number");
println!("Enter power: ");
io::stdin().read_line(&mut input2).expect("Not a valid string");
p = input2.trim().parse().expect("Not a valid number");
res = n.pow(p);
println!("Result is: {}",res);
}
Output:
RUN 1:
Enter number:
2
Enter power:
3
Result is: 8
RUN 2:
Enter number:
10
Enter power:
3
Result is: 1000
RUN 3:
Enter number:
7
Enter power:
5
Result is: 16807
Explanation:
Here, we read the number and power from the user. Then we calculated the power of a given number using the pow() function and printed the result.
Rust Basic Programs »