Saturday, 25 June 2016

Modulus Operator not work with float in C/C++

float / double has 3 component .
1 - sign  -       This component in telling to the compiler that value is positive or negative (-/+).
                      0 for positive, 1 for negative
2 - exponent - This is the order of (power of ) magnitude .
3 - mantisa    - This is specifing the actual digit of number .

            raaaaaaaakkkkkkkkkkkkkkkkkkkkkkk
            31                                                       0
           r  --> sign
           a --> exponent
           k --> mantisa

Means-
            00000000000000000000000000000000

        31's digit specifying that value is negative or positive .
        after 8 digit specifying the exponent of value
       and after decimal place value is remain 23.

    If we try to use % operator with float point ,like

     5.23  % 3.5
compiler generate error, like


because % operator return the remainder  of operand . In these case compiler so confuse , which value is operate with operator .

If you want solution of it , then you can use fmod function of math.h in c/c++ .
then you can see no error .

 fmod function working :
     first fmod() function round of the float value , in corresponding integer and the operate with operator .. And return remainder in integer type and after that change the corresponding float value .

Reason for float error :-
 I hope so may be . 
--> With float value compiler will be confused that which value is compile .
--> % operator return remainder value in integer type .
--> Compiler not support the operator with float because bit level change in 3 step .


Note :  This issue  is solved all modern language . like (Java ,  C# , .Net etc ) .





No comments:

Post a Comment