i have a problem of geting a square root in c++ using (cmath)

Dani AI

Generated

Quick practical notes tied to the replies above.

As suggested, a minimal reproducer is the fastest way to diagnose. Common root causes are missing the right header/namespace, passing the wrong type and then being surprised by truncation or NaN, or expecting an integer result. was on the right track about using floating types; ’s claim that sqrt(int) is “invalid” is misleading — integer arguments are converted to a floating type for the available overloads, so the call itself compiles, but the result is a floating value.

Example patterns to use (type and error handling shown):

#include <cmath>
#include <iostream>

int main() {
    int n = 16;
    double r = std::sqrt(n);            // r == 4.0 (sqrt returns floating type)
    int rounded = static_cast<int>(std::lround(r)); // convert safely if an integer is wanted
    std::cout << r << " -> " << rounded << '\n';
}

Negative inputs and domains: the real sqrt functions produce NaN for negative real inputs. To get complex results use the complex overloads:

#include <complex>
#include <iostream>

std::complex<double> c = std::sqrt(std::complex<double>(-9.0, 0.0)); // yields 0+3i
std::cout << c << '\n';

If the compiler/linker reports missing symbols when building C code, link the math library (for C: add -lm). In C++ the <cmath> overloads live in std:: — prefer std::sqrt to avoid portability issues. For exact behavior and overload list see the library reference: std::sqrt reference and the complex overloads: complex::sqrt reference.

Recommended Answers

All 3 Replies

Hey,

Could you describe the problem? Give us some more info on "what" the problem is?

If you went to a garage with a car and said, "its broken" they wouldnt know what was going on. Same goes here.

post up the

// code that
// your trying to use

Maybe also check the "cmath" #include <cmath> statement?

-Harry

How to use sqrt function in c++ :

int a = 3;
float b = 3;
double c = 3;

float t = sqrt(a); //invalid error. a is of type int. Only float|double allowed
float y = sqrt (  float(a) ); //valid because of typecast
float u = sqrt(b); //valid because b is of type float 
float h = sqrt(c); //valid because c is of type double
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.