C++ program: I will put the program next post
Why root 8.33 as an integer is 2.82843 ??
Because you declared ` int l = 8.33; `, so because you cast ` l ` as an ` int ` you stored the value ` 8 ` instead of ` 8.33 `. You then later recast ` l ` as a ` float `, but that just makes it the value ` 8.0 `, and \(\sqrt{8.0}\approx2.82843\) If you cast something as an ` int `, it is telling your OS to reserve a certain number of bits for that value (the number of bits depending on the architecture of your machine). A ` float ` requires twice as many bits to be stored as an ` int `, so when you say ` int a = 2.5 ` it is like trying to put something in a box that is too small, so the compiler just leaves out the memory that doesn't fit and stores the integer part.
oh..uh I thought i wrote is 4 , I looked for just 2 :P Thanks a bunch.
Integers and floats are represented in entirely different ways in memory. Integers are usually 2's complement whilst floats are IEEE 754 (although this can differ in some architectures). "A float requires twice as many bits to be stored as an int ...". Not really, this is dependent on system architecture and compiler implementation. In java int and float are both defined as 32-bit. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html In c++ one can run the following program ```java #include <iostream> #include <climits> #include <cfloat> using namespace std; int main() { // 32 bit 2's comp int and 32 bit IEEE 754 float theoretical max vals cout << "2147483647 : 3.4028234*10^38" << endl; // int and float actuall vals on this system cout << INT_MAX << " : " << FLT_MAX << endl; return 0; } ``` which returns ``` 2147483647 : 3.4028234*10^38 2147483647 : 3.40282e+38 ``` on Ideone ( http://ideone.com/3B349g ) implying they can have the same byte size. As for the how actual truncation works I'm unsure but from what I've read the the compiler adds/uses some kind of truncation-function when it detects float to int casting.
@Lyrae My mistake, I had confused ` float `s with ` double `s. It seems that the truncation happens because the compiler is forced by the given type to use a specific representation of the given number, because ` int `s are represented by the 2's compliment system, and ` float `s devote a certain number of bits to the mantissa, the exponent, and one for the sign. http://stackoverflow.com/questions/7079468/size-of-int-and-float
Join our real-time social learning platform and learn together with your friends!