Printf use mismatch

I am using Code Block with the GNU GCC compiler. And I'm trying to use 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 is a result for input value 10

987388755  
3

what's wrong with this code?

+5
source share
3 answers

sqrt returns double:

double sqrt(double x);

You need:

printf("\n%g",sqrt(number));
+10
source

Using the wrong format specifier in printf()calls Undefined Behaviour. sqrt()returns double, but you are using %d.

+6
source

Edit:

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

at

printf("\n%g",sqrt(number));

Please note that sqrt()returns double, and not int- your compiler should warn you about this if you have warnings. for example gcc -Wall ...(and if you have no warnings, then it's time to get used to it).

0
source

All Articles