0
How do you input square root in C++
If I use √ here, it will eventually said error and read out a bunch of weird things. Please help!
6 Antworten
+ 6
/*what I know you should use mathmatical functions
and to get the root use sqrt() function.*/
#include <cmath>
int x=4;
cout<<sqrt(x) //output is 2 .
/* for your info : other mathmatical function :
pow() :pow(2,5)..return 32
abs() :abs(-5).. return 5
+ 2
#include <math.h>
int main(){
double x =144.0;
x = sqrt(x);
}
Use sqrt from math.h?
Your question isnt very clear on what you mean
+ 2
If I'm right, what you want is to do this :
int n;
cin >> n;
cout << n;
if you enter "√25" you want it to return 5.
The problem is that there is no simple function to do that (i think)
What i suggest you is :
- always make input as string
- then if the string are supposed to be number, try to cast them in a special function you will create that will be something like :
double toNumber(std::string const& str)
- you can use <regex> to use regular expression and check wether the string is similar to a number or not (here you can include the possibility of having a √ symbol in the string)
- then you can handle two cases :
* there is not the √ symbol so you can easly convert your string into a double with the std::atof function.
* there is the √ symbol so here you should remove it calculate the number under the square root, then check wether it is a positive number or not and then return if possibly the square root of that number using tge sqrt function from <cmath>
- you will have to handle exception with this function i see two kinds of errors :
* the input doesn't match with your regex so your string doesn't represent a number.
* the square root is used for a negative number.
the code will run as follow :
std::string input;
std::getline(std::cin, input);
try
{
std::cout << toNumber(input);
}
catch(...)
{
//...
}
+ 2
edit :
Using the √ symbol in string might be a problem. Because it is a "special" character and so tou will need more than one char to handle it.
You might use an other symbol a a seauence of symbols like "sqrt" instead of "√" in your regex and strings.
Else you should consider using the wstring the wcout, the wcin with a w each time.
+ 1
Hi Shrey,
This is relatively easy to crack. There are two-three methods which you may try. See here - https://myeasytuts.com/square-root-cpp-sqrt-function/
0
System.out.print(Math.sqrt(x));