Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sqrt() problem

Status
Not open for further replies.

kimhoong79

Technical User
Jun 10, 2002
58
MY
Recently I found out some problem with sqrt(). Here's the code:

#include <stdio.h>
#include <math.h>

main()
{
int Result, Data = 4;

printf("%d\n", sqrt(Data));

Result = sqrt(Data);
printf("%d\n", Result);
}

The output of this code is

0
2

which for me, is not consistent. Can anyone explain this to me? Thanks in advance
 
Hi:

Not near a development box so I can't check it out, but the sqrt function returns a double not an int. Your complier is automatically casting the return to an int which is why the second example works.

You might try the %f option with the first example.

Regards,


Ed
 
Code:
#include <stdio.h>
#include <math.h>

main()
{
   int Result, Data = 4;

   printf("%d\n", (int)sqrt(Data)); // should work
   printf("%f\n", sqrt(Data)); // should work

   Result = sqrt(Data);
   printf("%d\n", Result);
}

Pragmatic programmer tip related to this issue:
Select is not broken.

In most cases, the libaries are written correctly, it is almost always a case of your code being broken. If the library is broken a quick goole search would yeild a lot of hits about people complaining. The error is generally in your use of the library, or errors arround the use of a call to a library function.

[plug=shameless]
[/plug]
 
No any casting in printf() args after the 1st because of this function prototype:
Code:
int printf(const char*,...);
It's unsafe output: a compiler can't verify arg types. So printf("%d",(double)...) is wrong in all cases...

Moreover: sqrt(4) may be not equal to 2 exactly, so (int)sqrt(4)) is equal 1 or 2 - both results are correct (it's not a language problem: it's floating point arithmetic;)...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top