我试图在临时转换为整数(四舍五入)的 double 上实现 mod 运算符,但编译器 (clang) 似乎不喜欢那样并返回错误:assignment to cast is非法,不支持左值转换
。
例如,在这个片段中
double a;
int b;
(int)a %= b;
有没有办法绕过这个限制?
最佳答案
你的行为是违法的。说 (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 的值高于 int
的范围,那么这会产生未定义的行为。
关于c++ - 您如何合法地对舍入 double 执行 mod 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40734573/