user994165
user994165

Reputation: 9512

Convert int to double

I ran this simple program, but when I convert from int to double, the result is zero. The sqrt of the zeros then displays negative values. This is an example from an online tutorial so I'm not sure why this is happening. I tried in Windows and Unix.

/* Hello World program */

#include<stdio.h>
#include<math.h>

main()

{  int i;

   printf("\t Number \t\t Square Root of Number\n\n");

   for (i=0; i<=360; ++i)
        printf("\t %d \t\t\t %d \n",i, sqrt((double) i));


}

Upvotes: 5

Views: 82654

Answers (3)

Artur
Artur

Reputation: 7267

The problem is incorrect use of printf format - use %g/%f instead of %d

BTW - if you are wondering what your code did here is some abridged explanation that may help you in understanding:

printf routine has treated your floating point result of sqrt as integer. Signed, unsigned integers have their underlying bit representations (put simply - it's the way how they are 'encoded' in memory, registers etc). By specifying format to printf you tell it how it should decipher that bit pattern in specific memory area/register (depends on calling conventions etc). For example:

unsigned int myInt = 0xFFFFFFFF;
printf( "as signed=[%i] as unsigned=[%u]\n", myInt, myInt );

gives: "as signed=[-1] as unsigned=[4294967295]"

One bit pattern used but treated as signed first and unsigned later. Same applies to your code. You've told printf to treat bit pattern that was used to 'encode' floating point result of sqrt as integer. See this:

float myFloat = 8.0;
printf( "%08X\n", *((unsigned int*)&myFloat) );

prints: "41000000"

According to single precision floating point encoding format. 8.0 is simply (-1)^0*(1+fraction=0)*2^(exp=130-127)=2*3=8.0 but printed as int looks like just 41000000 (hex of course).

Upvotes: 8

pmg
pmg

Reputation: 108986

sqrt() return a value of type double. You cannot print such a value with the conversion specifier "%d".

Try one of these two alternatives

        printf("\t %d \t\t\t %f \n",i, sqrt(i)); /* use "%f" */
        printf("\t %d \t\t\t %d \n",i, (int)sqrt(i)); /* cast to int */

The i argument to sqrt() is converted to double implicitly, as long as there is a prototype in scope. Since you included the proper header, there is no need for an explicit conversion.

Upvotes: 3

Erick Smith
Erick Smith

Reputation: 930

Maybe this?

int number;
double dblNumber = (double)number;

Upvotes: 19

Related Questions