Monday, August 22, 2011

Tip: C\C++ Logical Error on Division

Logical errors are the worst nightmare, even for a senior programmer. As experience is gained such issues are getting more and more familiar to recognize and avoid them. Though tips should be always welcomed, especially for the newcomers.

Enough with the much talk! take  good look at this:

void main() { float n=0; n=7/3; printf("%f", n); }

So what the printf() you think would print?

The most of you expect something like 2.333..

Though theory is pretty strict!

Your Co. Sci. Teacher: 

"You may not have a float result by dividing two integers, not even when the result is stored in a float variable."

and so you should have printed: 2

The reason of this failure lays to your integer/integer division. 

So in order to achieve a float result, you should write:

void main() { float n=0; n=7.0/3.0; printf("%f", n); }

Always note:

    int/int == int
    float/int == float
    int/float == float
    float/float == float

Have fun! :) 

No comments:

Post a Comment