![]() |
How do I take a square root?
I was making a program just to make sure I can, and I decided to make a pythagorean theorem program. what happened is I defined
"C" as C = ( A * A ) + ( B * B ) which gives the wrong answer, because the formula is supposed to be C square = A squared + B squared. Anyway, my question is in the title: is there any way I can just take the square root of ( A * A ) + ( B * B ) ? If so, thanks. If not... and anybody has any good ways that I could accomplish the same thing, please let me know. thanks! |
sqrt((a*a)+(b*b));
|
What niteice said. But you must also include the math.h library.
:
#include <math.h>Then, for sake of listing alternatives, you can also do... :
x_sqrt = pow(x, 0.5)Although I'm not sure if "pow" accepts a float as a second argument. |
ok, thanks. out of curiosity... what if I wanted to use the variable C.
So I would have C = ( A * A ) + (B * B ) then I would have sqrt (C). But that doesn't work, due to me not defining the variable or something like that. I'd appreciate it if somebody can tell me the proper way to make that work... and I'd appreciate it even more if somebody can explain WHY it works that way. thanks. you guys are amazing. btw, the reason linux gave me that it would work is because "called object is not a function" |
If C is not defined, then define it! Wherever you define "A" and "B", just add in "C" to define it as well.
If that's not the problem, you can post your code (wrapped in [code][/code] tags), and we could give you further assistance. :) |
C was defined, as far as I know. It said "float A, B, C ; " which I think, at least, defines C. Anyway, code will be edited in here
:
#include <stdio.h> |
The function "sqrt" accepts an integer value. You are giving it a float. This can be fixed by using the function "sqrtf". The "f" on the end is there because it will accept a float as its parameter, just as "sqrtl" accepts a long integer.
New Code: :
C = ( A * A ) + ( B * B ) ; And I don't want to confuse you, but it's important to note that it can also be rewritten as: :
C = sqrtf ( ( A * A ) + ( B * B ) ); |
Thanks. and for the record, I understand mathematics, I am mostly just a noob at programming & chemistry. Lol. Thanks for all the help though.
|
It still does not work though. If i remove "sqrtf" from the variable declaration (where it says float A, B, C, sqrtf ; ) the compiler tells me that there is a "implicit differentiation of function sqrtf" and that there is an "undefined reference to sqrtf."
If I leave sqrtf in the variable declaration, it says that on line 21 (the line where it says C = sqrtf (C) ) there is an "error: called object is not a function." wth??!!! haha |
you declared sqrt to be a float.. then you try to call it as a function???
|
| All times are GMT -5. The time now is 10:36 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC