的"含义;%QUOT;在C#中操作的数字式双 [英] Meaning of "%" operation in C# for the numeric type double
问题描述
最近,我发现,C#的运营商%
适用于一倍。尝试了一些东西出来,毕竟想出了这个测试:
Recently I discovered that C#'s operator %
is applicable to double. Tried some things out, and after all came up with this test:
class Program
{
static void test(double a, double b)
{
if (a % b != a - b * Math.Truncate(a / b))
{
Console.WriteLine(a + ", " + b);
}
}
static void Main(string[] args)
{
test(2.5, 7);
test(-6.7, -3);
test(8.7, 4);
//...
}
}
在
一切本次测试工作。
是 A%B
总是等同于 A - B * Math.Round(A / B)
?如果没有,请向我解释如何运营商真正的作品
Everything in this test works.
Is a % b
always equivalent to a - b*Math.Round(a/b)
? If not, please explain to me how this operator really works.
编辑:接听詹姆斯L,我明白,这是一个模运算符和一切。我只是关于它如何与双,整数我明白了工作的好奇。
Answering to James L, I understand that this is a modulo operator and everything. I'm curious only about how it works with double, integers I understand.
推荐答案
模运算符适用于浮点值以同样的方式,因为它用于整数。所以考虑一个简单的例子:
The modulus operator works on floating point values in the same way as it does for integers. So consider a simple example:
4.5 % 2.1
现在,4.5 / 2.1约等于2.142857
Now, 4.5/2.1 is approximately equal to 2.142857
因此,该师的整数部分为2。2减法* 2.1 4.5和你有滞留者,0.3
So, the integer part of the division is 2. Subtract 2*2.1 from 4.5 and you have the remainer, 0.3.
当然,这个过程是受浮点表示性问题,所以要小心 - 你可能会看到意想不到的效果。例如,看到这个问题在这里问及堆栈溢出:浮点运算 - 模运算符的双师型
Of course, this process is subject to floating point representability issues so beware – you may see unexpected results. For example, see this question asked here on Stack Overflow: Floating Point Arithmetic - Modulo Operator on Double Type
是一%b总是等同于 - ?b * Math.Round(A / b)
Is a % b always equivalent to a - b*Math.Round(a/b)?
没有事实并非如此。下面是一个简单的反例:
No it is not. Here is a simple counter example:
static double f(double a, double b)
{
return a - b * Math.Round(a / b);
}
static void Main(string[] args)
{
Console.WriteLine(1.9 % 1.0);
Console.WriteLine(f(1.9, 1.0));
Console.ReadLine();
}
至于你需要参考的是如何规定的模运算的精确细节到C#规范 - 。 earlNameless的回答给你一个链接到
这是我的理解是 A%b
实质上等同,模浮点精度,以 A - b * Math.Truncate(A / b)
。
It is my understanding that a % b
is essentially equivalent, modulo floating point precision, to a - b*Math.Truncate(a/b)
.
这篇关于的"含义;%QUOT;在C#中操作的数字式双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!