• C

I want to use Sqrt ... but it doesnt work !

Hi.
I am new in c... Just beggining :)

I want to know why sqrt doesnt work !
I use it like that :

#include <stdio.h>
#include <math.h> // I thought that this is useful...

main () {
 double number1,number2;
 
  number1=16;
  number2=sqrt(number1);
 
  printf("The square root of 16 is %d",number2);
}

I always get 0.
I've tried printf with %e,%f,%d i've also tried to declare the variables as integer,float,double...

Always 0.
What am i doing wrong ?

Thanks :)
LVL 16
CodedKSenior Software EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sunnycoderCommented:
Hi CodedK,
> I've tried printf with %e,%f,%d i've also tried to declare the variables
> as integer,float,double...
try %Lf

Cheers!
sunnycoder

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CodedKSenior Software EngineerAuthor Commented:
0.00000 !!!
sunnycoderCommented:
Ignore previous post .. %Lf is for long doubles .. %f should work fine ... I tried with VC++ 6 ... it worked fine!
CodedKSenior Software EngineerAuthor Commented:
seconds after %Lf i've tried %f...
0.00000

I compile it in WATCOM. Dont have VC :(
callrsCommented:
A C++ example here which may work in C
http://www.cplusplus.com/ref/cmath/sqrt.html     C++ reference: cmath: sqrt

Based on that,
 number1=16;
may need to be
 number1=16.0;
sunnycoderCommented:
16 would get autmatically upcasted to double ... .0 should not be the issue ...
Any compiler options?
Any error or warning messages?
Also pls copy paste the exact output.

Can you run it through a debugger? if yes, then apply a breakpoint just before printf and examine contents of number2
CodedKSenior Software EngineerAuthor Commented:
#include <stdio.h>
#include <math.h>

main(){
double a,b,c,d,x1,x2;

 printf("2nd grade equation solver ...\n");
 printf("   (ax*x+bx+c)\n\n\n");
 
 printf("Input a :");
 scanf("%d",&a);
 printf("\nInput b :");
 scanf("%d",&b);
 printf("\nInput c :");
 scanf("%d",&c);

 d=(b*b);
 d=d - (4*(a*c));     // I broked the command in many coz i thought the error was here !
 
 if (d>0) {
  printf("(d >0)... 2 solutions !\n");  
 
  x1=sqrt(d);   // I broked the command in many coz i thought the error was here !
  x1=x1-b;
  x1=x1 /(2*a);
  printf("x1 = %d\n",x1);

  x2=sqrt(d);
  x2=x2-b;
  x2=x2 / (2*a);
  printf("x2 = %d\n",x2);
 }

 if (d==0) {
  x1=(-b) / (2*a);
  printf("Only solution : (x=%d)",x1);
 }

 if (d<0) {
  printf("No solution... (D<0");
 }
}

~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
Another try ... now i get -25878
callrsCommented:
Try 16.0 anyway...
Also try the example from that site, then replace parts with your own code & test after each adjustment to find the bug in yours
sunnycoderCommented:
#include <stdio.h>
#include <math.h>

main(){
double a,b,c,d,x1,x2;

 printf("2nd grade equation solver ...\n");
 printf("   (ax*x+bx+c)\n\n\n");
 
 printf("Input a :");
 scanf("%lf",&a); >>>>>>>>>> wrong input format specifier for all 3 variables
 printf("\nInput b :");
 scanf("%lf",&b);
 printf("\nInput c :");
 scanf("%lf",&c);

 d=(b*b);
 d=d - (4*(a*c));     // I broked the command in many coz i thought the error was here !

 if (d>0) {
  printf("(d >0)... 2 solutions !\n");  
 
  x1=sqrt(d);   // I broked the command in many coz i thought the error was here !
  x1=x1-b;
  x1=x1 /(2*a);

  x2=sqrt(d);
  x2=-x2-b; >>>>>>>>>>>> you had this identical to first root ... should have been -x2-b here
  x2=x2 / (2*a);
  printf("x2 = %f\n",x2);
 }

 if (d==0) {
  x1=(-b) / (2*a);
  printf("Only solution : (x=%d)",x1);
 }

 if (d<0) {
  printf("No solution... D<0");
 }
}
sunnycoderCommented:
forgot ... you were printing with %d ... should have been %f ... can never emphasize enough the need for matching format specifiers with the arguments ... C does not perform any kind of type checking .... you have to be very careful in this regard ... One of the common but hard to detect source of error!!
callrsCommented:
Still seems unanswered:     The claim that %f won't work in the original question...
sunnycoderCommented:
callrs,

I am not sure what are you trying to suggest by claiming that question has not been answerd while asker has closed the question on their own. Can you please elaborate?

Also - "wont work" is quite different from "is not working"

sunnycoder.
callrsCommented:
>>seconds after %Lf i've tried %f...
>>0.00000

Not suggesting anything, other than to clear up confusion for anyone reading the thread. %f is claimed to not work in original code...So it would  make an interesting reference to know 'why?'
sunnycoderCommented:
>So it would  make an interesting reference to know 'why?'
http:#17489782 ... It helps to read the thread in entirity!!
CodedKSenior Software EngineerAuthor Commented:
Hi callrs
double number1,number2;
should be
float number1,number2;

and then use %f

thats what i understood
sunnycoderCommented:
CodedK

You are right ... Earlier you were reading in a double using int format specifier ...

If you are reading in with incorrect format specifier, you would be reading in incorrect values and hence the errors in values being printed.

floats with %f matches ... hence it works ... anything will as long as format specifier and argument match.

sunnycoder
CodedKSenior Software EngineerAuthor Commented:
Thats what i understood from your post ... maybe callrs is right too coz
i had to work with Watcom compiler in Dos environment and maybe this alters the results somehow.

Thank you both. :)
sunnycoderCommented:
Results for standard C program are not platform specific ... If they were to be standard specific, whole point of language specification would be lost!!!
callrsCommented:

CodedK, thank you for the solution & shedding a needed light on the issue for us and others who read this thread  : )
callrsCommented:
Some of what's been up:

1) Installed Watcom 1.5 last week. It has a bug -- won't produce a working exe on both the WinXP & the Win98 computer despite even re-installation. So this week, installed 1.4 & it worked great.

2) Ran your example & sure enough, there was an error. The "%Lf" suggested doesn't work.

3) Ran the example I gave to you in the link. Worked perfectly. All you needed to do was to look at that working code & then adapt it to yours : )

4) To adapt, there were 2 things we could have done. (Second worked for me, but if it doesn't for you then need would be to keep debugging...)

  a) As I suggested, try 16.0 instead of 16. This was no blind suggestion, but one based on experience that auto-casting doesn't always occur (e.g. for d=1023/5). Such lack of auto-casting has caused me apparently inexplicable trouble before until someone suggested to use a decimal place: Lo and behold, that fixed the problem!  :).  Though it ends up being not an issue here, my suggestion was really a debugging process we need go through to narrow down the possibilities.  This process is especially important for a beginner like you are to C; for me not to have mentioned it would not be fair to you...The process is also a great way to help others when an obvious solution is not immediately seen.

  b) Other option, if we continue in the search (as suggested: "Also try the example from that site, then replace parts with your own code & test after each adjustment to find the bug in yours"), is to use %lf instead of %d. And...it works, even without changing 'double' to 'float'. So the solution provided deserves credit, no? Hours have been spent now on this. Thanks has been given, and I appreciate that, but if you can re-assign (split) points that would be great as well (points are plenty, but, with a grade, something else matters more here)  : )


Cheers                                                                                                •   •

PaulCaswellCommented:
Hi callrs,

Perhaps I could help out.

Are you requesting a change to the points distribution of this question?

I can see that you spent a good deal of time with this thread and certainly deserve credit for that work. My concern is that essentially, sunnycoder's comments did lead asker to the answer they were looking for, i.e. it was the input formats at fault in the real code and the output formats in the sample code they posted.

I agree that your suggested method of finding the answer would definitely have worked but points are awarded for solutions on EE, not paths to solutions.

If you still feel that a split is the only fair outcome here and CodedK agrees, I would be quite happy to help make that happen.

Paul <Page Editor>
CodedKSenior Software EngineerAuthor Commented:
Hi

I am new in C, but i am a very old member here at EE. I also am a very old programmer (Pascal, Delphi, Php).
I know that a path to a solution is a solution.

From EE help :
What's the right grade to give?
A: The Expert(s) either provided you with a thorough answer or they provided you with a link to information
that thoroughly answered your question. An "A" can also be given to any answer that you found
informative or enlightening beyond the direct question that you asked.

When Sunnycoder and Callrs gave answers at the same time i was trying to see whats the problem too.
Every suggestion made i tried it. I really really tried 16.0 even before yoiu suggest it callrs. BUT the code
had many bugs so i couldnt figure out what was the right replacement.
It all worked fine when i changed double to float.
I am also sure that you know better. And i would like to split the points. So Paul please reopen this thread so i can split
between Sunnycoder and Callrs.

I'll appreaciate your help in my future questions :)
CodedK.
sunnycoderCommented:
I am afraid that using 16.0 in place of 16 was nowhere close to being a solution to the problem ...

Whatever long and involved debugging they might have carried out, the bug that they would have found would have been format specifiers ... which I correctly pointed out in the first place ... That how they would arrive at format specifiers starting from 16.0 is something I cant easily imagine.

Singing about how a beginner should follow the long winded unearthly debugging and posting a link to sqrt function in first post does not seem to gel well ... Neither does the fact that solution of using 16.0 was quoted to be sourced from online example mix well with the claim that it was from personal experience ...

The string of questions after PAQing clearly demonstrates inability to understand a perfectly fine, working solution. I suspect one would have arrived at "solution" if they cant understand it when it is in front of their eyes.

Awarding for long slog and efforts is one thing ... awarding for solution is entirely different.
CodedKSenior Software EngineerAuthor Commented:
Sunnycoder are you refering to me with this :
>>The string of questions after PAQing clearly demonstrates inability to understand a perfectly fine, working solution..

I didnt ask anything, i accepted your solution as a solution from the start.
sunnycoderCommented:
CodedK,

I was not refering to you in my post http:#17651337

Your participation in the question was perfectly fine in my view. Sorry if the above post gave an impression otherwise.

sunnycoder
CodedKSenior Software EngineerAuthor Commented:
Its not abandoned ! I left it to you to deside.
Thanks.
callrsCommented:

~ Respect ~

In another post I defended an asker by saying: without the user, there's no need for us experts. User is more of an expert -- the one who defines the need, the end result that needs to come to pass. Think about that before...

Issue here is unique in that it's first question I've seen where one expert disputes an asker's well-explained decision for a split, going against a common theme amongst the admins/mods at CS that they respect an asker's good judgement & do not like to second-guess.  To counter an asker's wish to share for value given sets an unworthy precedent & may not reflect well on the expert who opposes...besides making it an uncomfortable stressful unduly time-consuming and intimidating experience for others concerned. Forum should be about helping people while respecting & encouraging their natural desire to award help, besides also about motivating other experts. To help someone on a technical issue (as per symptom) but to degrade him/her/others on the more important success-inducing motivational and morale issue (cure)...can that be good?

I haven't even looked at the other thread you directed me to Paul, fearing more intimidation and misrepresentation on the heels also of another issue that popped up (an issue of extreme insensitivity that's totally vanquished my stamina in the past month while leaving me misspelling even my own id and misjudging even some simple technical issues). If you still doubt, then you may want to wait 'til mid-month when I ought to be in a better position to communicate. Let's not strain hearts...but give 'em a spark; don't fight in spite...be bright alight :)

This should not be a flaming war when a respectful (and in this case eloquent, a luxury not all have) asker's wishes should be respected; but, if another technical viewpoint is needed, feel free to copy to here this (http://www.geocities.com/callrs/q_21984069_a1.htm) abridged version of the earlier post.

To quote byundt (Brad), "Hoping to be helpful,"

-rs-

CodedK et al, best wishes & hope we all get the respect needed and deserved.

CodedKSenior Software EngineerAuthor Commented:
I increased the value of the question from 125 to 250 so that nobody should feel unhappy. :)

Its like both of you answered !

Both of you spend time (much more than needed) for my question :)

Dont fight :)
PaulCaswellCommented:
Nice thoughts callrs, very close to my opinion in many ways.

I can assure you any posts in my CS thread would NOT have been intimidating nor misrepresentations or they would have been removed. I respect your decision not to post.

If at any time you have further difficulties that I can help with, please do not hesitate to contact me. I am sure an old-timer like you ;-) will know how.

Thank you again for you patience CodedK.

Paul
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.