我正在编写一个用于区间运算的C#库,为此我需要 将浮点运算舍入模式设置为Up和Down。我知道在C ++中 它可以通过fesetround()函数实现。在C#中是否存在等价物, 或者如果没有,我怎么能以另一种方式实现呢?
答案 0 :(得分:1)
Math.Ceiling(num) // Rounds up
Math.Floor(num) // Rounds down
答案 1 :(得分:1)
我遵循了Pascal Cuoq的建议并创建了一个非常简单的功能组件。 如果其他人遇到这样的问题,我会在这里发布。
使用我的lib解决方案:
用法:
static void RoundModeConfig::setround( int mode );
// mode can be set to one of the following values:
static int RoundModeConfig::UPWARD
static int RoundModeConfig::DOWNWARD
static int RoundModeConfig::DEFAULT // To nearest mode.
static int RoundModeConfig::TOWARDZERO
感谢Hans Passant的建议,我应该牢记这一点。 感谢大家的帮助,希望有人会发现我的dll很有用:)
答案 2 :(得分:1)
对于窗户:
/// <remarks>
/// https://en.cppreference.com/w/cpp/numeric/fenv/FE_round
/// </remarks>
public enum RoundMode
{
/// <summary>
/// Rounding towards nearest representable value.
/// </summary>
FE_TONEAREST = 0x00000000,
/// <summary>
/// Rounding towards negative infinity.
/// </summary>
FE_DOWNWARD = 0x00000100,
/// <summary>
/// Rounding towards positive infinity.
/// </summary>
FE_UPWARD = 0x00000200,
/// <summary>
/// Rounding towards zero.
/// </summary>
FE_TOWARDZERO = 0x00000300,
}
public static class ExternMethods
{
[DllImport("ucrtbase.dll", EntryPoint = "fegetround", CallingConvention = CallingConvention.Cdecl)]
public static extern RoundMode GetRound();
[DllImport("ucrtbase.dll", EntryPoint = "fesetround", CallingConvention = CallingConvention.Cdecl)]
public static extern int SetRound(RoundMode roundingMode);
}