I want to take the square root of a number.
I looked at the documentation here, and wrote use std::num;
at the top of my program which I thought would have allowed me to sqrt
. This doesn't work though, so what do I need to do to actually use std::num::sqrt
?
let upperLimit: i64 = sqrt(num as f64) + 1; //doesnt work
I'm very new to Rust coming from c++, so I really don't understand that real use of use
.
The sqrt() function in C++ returns the square root of a number. This function is defined in the cmath header file. Mathematically, sqrt(x) = √x .
Method 1: Using inbuilt sqrt() function: The sqrt() function returns the sqrt of any number N.
sqrt() function is an inbuilt function in Python programming language that returns the square root of any number. Syntax: math.sqrt(x) Parameter: x is any number such that x>=0 Returns: It returns the square root of the number passed in the parameter.
Since Rust 1.0, the following should be used:
let upperLimit = (number as f64).sqrt() as i64 + 1;
Or, equivalently:
let upperLimit = f64::sqrt(number) as i64 + 1;
See the docs for f64::sqrt
.
Editor's Note: This historical answer predates Rust 1.0 and is no longer applicable.
With use std::num;
you "import" the whole module and access members with num::*
:
use std::num;
let upperLimit: i64 = num::sqrt(num as f64) + 1;
If you want to use sqrt
directly you have to import it as use std::num::sqrt;
:
use std::num::sqrt;
let upperLimit: i64 = sqrt(num as f64) + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With