0

我正在尝试在临时转换为整数(四舍五入)的 double 上实现 mod 运算符,但编译器(clang)似乎不喜欢这样并返回错误:assignment to cast is illegal, lvalue casts are not supported. 例如,在这个片段中

double a;
int b;
(int)a %= b;

有没有办法绕过这个限制?

4

1 回答 1

2

你的所作所为是非法的。说(int)a = ...是非法的,因为您不能a以这种方式转换为整数。您必须将其投射到作业的右侧。

如果你真的想这样做,你可以说:

double a;
int b;
a = (double)((int)a % b); /* Casting to a double at this point is useless, but because a is a double-type, the result of the modulus it will be implicitly casted to a double if you leave out the explicit cast. */

我建议将模数结果分配给一个新的 int 变量,但这是您的选择。


编辑:这是一个例子:http: //ideone.com/tidngT

此外,值得注意的是,将 double 转换为 int 并不会将其舍入,而是将其截断。而且,如果您的 double 的值高于 an 的范围int,那么这可能会产生未定义的行为。

于 2016-11-22T05:50:38.923 回答