Sunday, July 26, 2009

C code for sqrt?

#include%26lt;math.h%26gt;


int main()


{


int a,b;


printf("a");


scanf("%d",%26amp;a);


b=sqrt(a);


printf("%d",b);


return 0;


}





this is not working in unix. plz tell where the mistake lies.


or any code for sqrt()

C code for sqrt?
Hmm tried to compiler it for windows, only real bug was compiler didn't know whether to cast sqrt's argument as a double or a float, damn things been overloaded to support either and it couldn't decide which we'd prefer!





so changing "b=sqrt(a);" to "b=sqrt((float)a);" will make it compile, we'd also add a .5f to it if we wanted better rounding. and we should check that b is no negatiive before calling sqrt I think. Otherwise using doubles or floats would be better usually.





Also did you mean to print the value of the valible a instead of the letter "a"(that just seemed an odd thing to print to me).





So I think you want:


float a,b;


while (true)


{


scanf("%f",%26amp;a);


if (a%26gt;=0) break;


printf("Please enter a positive number!\n");


}


b=sqrt((float)a);


printf("The Sq Root of %f is %f\n",a,b);


return 0;
Reply:sqrt() does not return type int, returns type double


No comments:

Post a Comment