Why is modulus operator not working for double in c#?

前端 未结 6 1057
粉色の甜心
粉色の甜心 2020-11-30 10:21

Consider this:

double x,y;
x =120.0;
y = 0.05;

double z= x % y;

I tried this and expected the result to be 0, but it came out 0.04933333.<

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 11:11

    You could do something like:

    double a, b, r;
    
    a = 120;
    b = .05;
    
    r = a - Math.floor(a / b) * b;
    

    This should help ;)

提交回复
热议问题