Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to double

Tags:

c

printf

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


}
like image 878
user994165 Avatar asked Nov 28 '22 22:11

user994165


2 Answers

Maybe this?

int number;
double dblNumber = (double)number;
like image 176
Erick Smith Avatar answered Jan 21 '23 18:01

Erick Smith


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

like image 40
Artur Avatar answered Jan 21 '23 17:01

Artur