Inconsistency using printf
Pregunta
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?
Solución
sqrt
returns a double:
double sqrt(double x);
You need:
printf("\n%g",sqrt(number));
Otros consejos
Using incorrect format specifier in printf()
invokes Undefined Behaviour
. sqrt()
returns double but you use %d
.
Change:
printf("\n%d",sqrt(number));
to:
printf("\n%g",sqrt(number));
Note that sqrt()
returns a double
, not an int
- your compiler should be warning you about this, so long as you have warnings enabled. e.g. gcc -Wall ...
(and if you don't have warnings enabled, then it's time to start making a habit of it).
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow