Saturday, May 22, 2010

Why is the following C code giving me no result ?

#include %26lt;stdio.h%26gt;








void main()


{


int i;


short r[6] = { 10,4567,4321,30897,5467,2};


float p[6] = {0,0,0,0,0,0};





for(i=0;i%26lt;6;i++)


{


p[i] = (float) (r[i]/32768);


printf("%.9lf\n", p[i]);


}


}

Why is the following C code giving me no result ?
It looks like you're trying to multiply (float) which has no definition or value times (r[i]/32768)
Reply:You are dividing an integer by an integer which always yields an integer. For fractions the result is truncated to zero.





The numerator needs to be cast as a float and then divide.





For example:





#include %26lt;iostream%26gt;





using namespace std;





int main( int argc, char* argv[] )


{


int small = 10;


int big = 30;





int resultInt = small/big;


float resultFloatWrong = small/big;


float resultFloatRight = ((float) small)/big;





cout %26lt;%26lt; "resultInt: " %26lt;%26lt; resultInt %26lt;%26lt; endl;


cout %26lt;%26lt; "resultFloatWrong: " %26lt;%26lt; resultFloatWrong %26lt;%26lt; endl;


cout %26lt;%26lt; "resultFloatRight: " %26lt;%26lt; resultFloatRight %26lt;%26lt; endl;


}





Yielded the following:





[721] answers: g++ -Wall divide.cpp


[722] answers: ./a.out


resultInt: 0


resultFloatWrong: 0


resultFloatRight: 0.333333


[723] answers:


No comments:

Post a Comment