square root

how do I do square root in C++?
closed account (3CXz8vqX)
1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
    int variable = 16; //Var to square root

    std::cout << (variable >> 2);
}


*cough* It's a bit of a cheat to be honest but uses nothing you shouldn't have already learned. ^_^ Check the bitwise operators here...

http://www.cplusplus.com/doc/tutorial/operators/

If you lecturer asks, "Okay...how do I cube root" just increase the number to 3. >.>;

You can also check whether the result is an integer or not before deciding whether it's valid.
Last edited on
http://www.cplusplus.com/reference/cmath/sqrt/

Ravenshade has shown a bit-shift operation, which is an efficient but non-standard way to divide an integer by 4, and is off-topic here.
closed account (3CXz8vqX)
O.o why is it none standard, looks like a perfectly valid way to square root a number...
I said it was a non-standard way of dividing an integer by 4. The standard way is to use the / operator. And it is off topic as you well understand. Highly entertaining and amusing, but of no benefit to the OP.
closed account (3CXz8vqX)
Fair point. ^-^;
You can use the C++ Standard Library <cmath> and the function sqrt


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using std::cout;
using std::endl;

#include <cmath>
using std::sqrt;

//You can use "usign namespace std" instead of...

int main(){

int value=16;

cout<<sqrt(value)<<'\n'<<endl;

return 0; //indicate successful termination
}//end main 
Topic archived. No new replies allowed.