Inconsistency using printf
Asked Answered
G

3

5

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?

Goldofpleasure answered 30/4, 2012 at 10:36 Comment(1)
You're using the GNU GNU C Compiler?Rendition
E
9

sqrt returns a double:

double sqrt(double x);

You need:

printf("\n%g",sqrt(number));
Encephalo answered 30/4, 2012 at 10:38 Comment(0)
V
5

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

Vegetable answered 30/4, 2012 at 10:39 Comment(0)
M
0

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).

Mastic answered 30/4, 2012 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.