在C#中,如何像Google Calc一样实现模数? [英] In C#, how do I implement modulus like google calc does?
问题描述
我有一个代表形状的课. Shape类具有一个称为Angle的属性.我希望此属性的设置器将值自动包装在[0,359]范围内.
不幸的是,简单的_Angle = value % 360;
仅适用于正数.在C#中,-40 % 360 == -40
. Google calc 我想要的方式.该值应为320.
C#中最优雅的解决方案是什么?
这是到目前为止我最好的方法:
public double Angle {
get { return _Angle; }
set {
if ( value >= 0 ) {
_Angle = value % 360;
}
else {
_Angle = value - (360 * ((int)(value / 360) - 1));
}
}
}
谢谢大家,我现在有:
public double Angle {
get { return _Angle; }
set {
_Angle = (value % 360) + ((value < 0) ? 360 : 0);
}
}
..哪个更好:)
尽管这是针对Java的,但Java的模数也具有相同的行为. (即-40 % 360 == -40
).
以下代码应返回[0. 360),无论给定角度是正还是负.
public class Mod
{
public static int mod(int a, int b)
{
if (a < 0)
return b + (a % b);
else
return a % b;
}
public static void main(String[] args)
{
System.out.println(mod(40, 360)); // 40
System.out.println(mod(-40, 360)); // 320
System.out.println(mod(-400, 360)); // 320
}
}
请注意,当给定角度超过-360°时,此功能才起作用.
I have a class which represents a shape. The Shape class has a property called Angle. I want the setter for this property to automatically wrap the value into the range [0,359].
Unfortunately, a simple _Angle = value % 360;
only works for positive numbers. In C#, -40 % 360 == -40
. Google calc does it the way I want it. The value should be 320.
What's the most elegant solution in C#?
Here's the best way I've got so far:
public double Angle {
get { return _Angle; }
set {
if ( value >= 0 ) {
_Angle = value % 360;
}
else {
_Angle = value - (360 * ((int)(value / 360) - 1));
}
}
}
Edit:
Thanks guys, I now have:
public double Angle {
get { return _Angle; }
set {
_Angle = (value % 360) + ((value < 0) ? 360 : 0);
}
}
..Which is a lot better :)
Although this is for Java, Java also has the same behavior for modulus. (i.e. -40 % 360 == -40
).
The below code should return an answer from [0. 360), regardless of the given angle, positive or negative.
public class Mod
{
public static int mod(int a, int b)
{
if (a < 0)
return b + (a % b);
else
return a % b;
}
public static void main(String[] args)
{
System.out.println(mod(40, 360)); // 40
System.out.println(mod(-40, 360)); // 320
System.out.println(mod(-400, 360)); // 320
}
}
Note that works when the given angle is past -360.
这篇关于在C#中,如何像Google Calc一样实现模数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!