开发者

How to use % operator for float values in c

When I use % operator on float values I get error sta开发者_Python百科ting that "invalid operands to binary % (have ‘float’ and ‘double’)".I want to enter the integers value only but the numbers are very large(not in the range of int type)so to avoid the inconvenience I use float.Is there any way to use % operator on such large integer values????


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


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.


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);  


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;
}


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜