为什么模运算符不工作的双C#中? [英] Why is modulus operator not working for double in c#?

查看:172
本文介绍了为什么模运算符不工作的双C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下:

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

double z= x % y;

我想这和预期的结果为0,但它出来0.04933333。

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

不过,

x =120.0;
y = 0.5;
double z= x % y;

确实给了0正确的结果。

did indeed gave the correct result of 0.

这是怎么回事?

我试过 Math.IEEERemainder(双,双),但它没有返回0无论是。这是怎么回事吗?

I tried Math.IEEERemainder(double, double) but it's not returning 0 either. What is going on here?

另外,顺便说一句,什么是最合适的方式找到其余的在C#?

Also, as an aside, what is the most appropriate way to find remainder in C#?

推荐答案

双打从来没有准确值。 120可能是存储无损,但0.05不是。 0.5为1/2,所以它可以存储无损,你没有得到一个舍入误差。

doubles are never exact values. 120 is probably stored lossless, but 0.05 not. 0.5 is 1/2, so it could be stored lossless and you don't get a rounding error.

要具有准确的(十进制)号码,使用十进制代替。

To have exact (decimal) numbers, use decimal instead.

decimal x,y;
x =120.0M;
y = 0.05M;

decimal z = x % y;  // z is 0

这篇关于为什么模运算符不工作的双C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆