C#相当于IEEE 754余数()?

在C#中,是否与C99 / IEEE 754的remainder()功能完全等效?

运算符%(double x,double y)的C# language specification says“类似于用于整数操作数的运算符,但与IEEE 754定义不同(其中n是最接近x / y的整数)”.

举一个不同的例子,这个C#程序输出两个1:

using System;

public class Test
{
    public static void Main()
    {
        Console.WriteLine(5.0 % 2.0);
        Console.WriteLine(3.0 % 2.0);
    }
}

http://ideone.com/GBITYq

而类似的C程序输出1和-1:

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    printf("%f\n", remainder(5.0, 2.0));
    printf("%f\n", remainder(3.0, 2.0));
    return EXIT_SUCCESS;
}

http://ideone.com/HpuIVr

解决方法:

此方法实现IEEE 754剩余算法:

Math.IEEERemainder(double, double)

public class Test
{
    public static void Main()
    {
        Console.WriteLine(Math.IEEERemainder(5.0, 2.0));
        Console.WriteLine(Math.IEEERemainder(3.0, 2.0));
    }
}

// Output: 1, -1

http://ideone.com/b2Lvfx

上一篇:c – 将Unicode字符写入OStream


下一篇:SAE J1939协议学习笔记