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,所以为什么不编译?