为什么编译器无法告诉结果是一个整数

Avi*_*ner 0 c# compiler-construction modulus

我遇到了编译器这个有趣的行为:

如果我有

    public int GetInt()
    {
        Random rnd = new Random();
        double d = rnd.NextDouble();
        int i = d % 1000;

        return i;
    }
Run Code Online (Sandbox Code Playgroud)

我得到一个错误: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)

这实际上有意义的,因为1000可以是一个double,而结果modulo操作可能是double为好.

但在将代码更改为:

    public int GetInt()
    {
        Random rnd = new Random();
        double d = rnd.NextDouble();
        int i = d % (int)1000;

        return i;
    }
Run Code Online (Sandbox Code Playgroud)

错误仍然存​​在.
据我所知,编译器拥有所有信息,以确定modulo运算符的输出将是一个int,所以为什么不编译?

Tyl*_*D87 5

如果d是==到1500.72546,则计算结果int d%(int)1000将为500.72546,因此隐式转换为int将导致数据丢失.