Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistency using printf

Tags:

c

function

sqrt

I am using Code Block with GNU GCC Compiler. And I am trying this code

int number,temp;

printf("Enter a number :");
scanf("%d",&number);
temp = sqrt(number);
printf("\n%d",sqrt(number)); //print 987388755 -- > wrong result
printf("\n%d",temp); //print 3 -- > write result

return 0;

and in this code there are a result for input value 10 is

987388755  
3

what is wrong in this code?

like image 600
zxprince Avatar asked Apr 30 '12 10:04

zxprince


2 Answers

sqrt returns a double:

double sqrt(double x);

You need:

printf("\n%g",sqrt(number));
like image 84
codaddict Avatar answered Nov 15 '22 04:11

codaddict


Using incorrect format specifier in printf() invokes Undefined Behaviour. sqrt() returns double but you use %d.

like image 28
P.P Avatar answered Nov 15 '22 02:11

P.P