Square Root in c++

Sep 11, 2008 at 4:11pm
closed account (42hU7k9E)
Hi, this is my first post on this forum! I've just started to program in c++ in school, and I've already got a question, that I just can't seem to find out on the web.

I have to write a program that calcucates a hypotenuse of an rectangular(right) triangle.Things get messed up when I try to write down the forumula of the hypotenuse.

hypotenuse = √a^2+b^2

A little help please.
Sep 11, 2008 at 4:23pm
Are you allowed to use the math library or does everything have to be done with just loops and math? I can show you either way, but they're quite different.
Sep 11, 2008 at 4:32pm
closed account (42hU7k9E)
The thing has to be done with loops and math, but please show me both ways, i want to learn everything.
Sep 11, 2008 at 4:38pm
Let's not fool ourselves. The only way to properly calculate a square root is with sqrt(), defined in cmath.
pow(), also in cmath, calculates any power (as long as it's valid, of course).
Sep 11, 2008 at 4:44pm
good luck learning everything.

Anyway, the simple way to do this would be to include the math.h library:
http://www.cplusplus.com/reference/clibrary/cmath/

and use the sqrt():
http://www.cplusplus.com/reference/clibrary/cmath/sqrt.html
and pow():
http://www.cplusplus.com/reference/clibrary/cmath/pow.html
which are the square root and power functions respectively.

The other way...well...it's complicated for anything but whole number roots.
Will they be wanting decimal answers for the hypotenuse or are they only checking the special case triangles?
Sep 11, 2008 at 5:32pm
closed account (42hU7k9E)
Thank you for that valuable information, i appreshiate it.
Sep 11, 2008 at 7:18pm
Yeah, helios is pretty much right. I mean, there are methods for loop calculating square roots, but they're not very accurate (unless you use one of the really complicated ones).
Topic archived. No new replies allowed.