Question:
confused with the C++ cmath function sqrt()?
michael
2011-06-29 05:43:13 UTC
Hi There,

i'm trying to declare a variable with the square root function found in cmath. Code below.

double sqt_of_n = sqrt(n);

where n is of type int;

My IDE is Microsoft visual C++ and when trying to compile it, it is throwing up errors with this piece of code. Error below:

1>chapter4.cpp(98): error C2668: 'sqrt' : ambiguous call to overloaded function
1> C:\Program Files\Microsoft Visual Studio 10.0\VC\include\math.h(589): could be 'long double sqrt(long double)'
1> C:\Program Files\Microsoft Visual Studio 10.0\VC\include\math.h(541): or 'float sqrt(float)'
1> C:\Program Files\Microsoft Visual Studio 10.0\VC\include\math.h(127): or 'double sqrt(double)'

If i convert the int to double before using it works fine, I dont understand why i cant convert to double and square root at the same time. Is this just my IDE?

Many thanks
Three answers:
anonymous
2011-06-29 06:05:39 UTC
sqrt( ( (double) c ) ) should work.



It's saying, I don't know which method to use. Same method name, different signatures. Three different methods.
?
2016-05-15 11:00:26 UTC
You're not that far off. As others have said, %lf is needed. See my fixes below. As you see, I also recommend adding some simple input validation, otherwise you're subject to garbage out, if garbage is input. #include #include #define MAX_LINE_LEN 1024 char line[MAX_LINE_LEN]; int main(int argc, char *argv[]) {     double user_input, result;     printf("Enter a number. I will find the square root.\n");     fgets(line,MAX_LINE_LEN,stdin);     if (sscanf(line,"%lf", &user_input) == 1) {         result = sqrt(user_input);         printf("Square root: %.1f",result);     } else {         puts("invalid input.");     }     return 0; } #if 0 Sample runs: Enter a number. I will find the square root. 3 Square root: 1.7 Enter a number. I will find the square root. 82 Square root: 9.1 Enter a number. I will find the square root. x invalid input. Enter a number. I will find the square root. 225 Square root: 15.0 #endif
?
2011-06-29 06:05:09 UTC
there is no sqrt(int) function.



so if you want to give it an int you need to up cast.



doulbe sqt_of_n = sqrt( static_cast(n) );


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...