Note that there are some explanatory texts on larger screens.

plurals
  1. POIf-else block and unexpected results with float datatype. [Edited with one more question]
    primarykey
    data
    text
    <p>I compiled the following program with gcc 4.4.1 and I get unexpected output (Well, unexpected for me)</p> <pre><code>#include&lt;stdio.h&gt; int main() { float x=0.3, y=0.7; if(x==0.3) { if(y==0.7) printf("Y\n\n"); else printf("X\n\n"); } else printf("NONE\n\n"); } Output: NONE </code></pre> <hr> <pre><code>#include&lt;stdio.h&gt; int main() { float x=0.3, y=0.7; if(x&lt;0.3) { if(y==0.7) printf("Y\n\n"); else printf("X\n\n"); } else printf("NONE\n\n"); } Output: NONE </code></pre> <hr> <pre><code>#include&lt;stdio.h&gt; int main() { float x=0.3, y=0.7; if(x&gt;0.3) { if(y&gt;0.7) printf("Y\n\n"); else printf("X\n\n"); } else printf("NONE\n\n"); } Output:X </code></pre> <p>So, it's clearly visible that the stored value in "x" is greater than 0.3 and the stored value in "y" is less than 0.7</p> <p>Why is this happening? Is this a property of float datatype or the if-else statements interpret float in a different way?</p> <p>Thanks.</p> <hr> <p>Edit: Alright, I pondered it over and I'm getting a little confused now. Kindly tell if my understanding of this problem is correct or not.</p> <pre><code>float x=0.3; </code></pre> <p>This stores <code>x=0.30000001192092895508</code> in the memory. Clearly, this is greater than <code>0.3</code> (Is this correct?) </p> <p>Now, <code>double x=0.3</code> results in <code>x=0.29999999999999998890</code> and this is smaller than 0.3 (Is this correct too?)</p> <p>Main question: So if I use store <code>0.3</code> in <code>float x</code>, then the following statement <code>if(x&gt;0.3)</code> results in <code>x=0.30000001192092895508</code> being implicitly casted as a double and 0.3 is also a double instead of a float. Hence <code>0.3=0.29999999999999998890</code> and the internal operation is <code>if((double) 0.30000001192092895508 &gt; (double) 0.29999999999999998890)</code>. Is this correct?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload