How to use % operator for float values in c

前端 未结 6 443
故里飘歌
故里飘歌 2020-12-03 14:30

When I use % operator on float values I get error stating that \"invalid operands to binary % (have ‘float’ and ‘double’)\".I want to enter the integers value only but the n

相关标签:
6条回答
  • 2020-12-03 15:18

    The % operator is only defined for integer type operands; you'll need to use the fmod* library functions for floating-point types:

    #include <math.h>
    double fmod(double x, double y);
    float fmodf(float x, float y);
    long double fmodl(long double x, long double y);  
    
    0 讨论(0)
  • 2020-12-03 15:24

    If you want to use an int use long long, don't use a format that is non-ideal for your problem if a better format exists.

    0 讨论(0)
  • 2020-12-03 15:29

    You can use the fmod function from the standard math library. Its prototype is in the standard header <math.h>.

    0 讨论(0)
  • 2020-12-03 15:29

    You're probably better off using long long, which has greater precision than double in most systems.

    Note: If your numbers are bigger than a long long can hold, then fmod probably won't behave the way you want it to. In that case, your best bet is a bigint library, such as this one.

    0 讨论(0)
  • 2020-12-03 15:29

    consider : int 32 bit and long long int of 64 bits

    Yes, %(modulo) operator isn't work with floats and double.. if you want to do the modulo operation on large number you can check long long int(64bits) might this help you.

    still the range grater than 64 bits then in that case you need to store the data in .. string and do the modulo operation algorithmically.

    or either you can go to any scripting language like python

    0 讨论(0)
  • 2020-12-03 15:30

    When I haven't had easy access to fmod or other libraries (for example, doing a quick Arduino sketch), I find that the following works well enough:

    float someValue = 0.0;
    
    // later...
    
    // Since someValue = (someValue + 1) % 256 won't work for floats...
    someValue += 1.0; // (or whatever increment you want to use)
    while (someValue >= 256.0){
        someValue -= 256.0;
    }
    
    0 讨论(0)
提交回复
热议问题