从 double 转换为 int - Visual C++/CLI 中的警告
我有一个 C++/CLI 中的双精度属性,我需要将其转换为整数,但当我这样做时,编译器会向我发出警告 (c4244)。例如:
//"Value" is a double
int newValue = (int)(control->Value); //C4244
我知道编译器不高兴,因为 double 可能大于 int 可以容纳的值,但这个特定的控件保证是 1 到 10 之间的值,所以我知道一切都会好起来的。我可以以某种方式消除这个警告吗?
I have a property that's a double in C++/CLI that I need to cast to an integer, but the compiler gives me a warning (c4244) when I do so. For example:
//"Value" is a double
int newValue = (int)(control->Value); //C4244
I understand that the compiler isn't happy because a double might be larger than an int can hold, but this particular control is guaranteed to be a value from 1 to 10, so I know that it will be okay. Can I eliminate this warning somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编译器警告您不仅可能超出范围,而且可能会丢失信息(它需要以某种方式对数字进行舍入,并且害怕自己这样做)。
使用
floor()
告诉它你知道你在做什么:或者你可以显式转换只是告诉编译器没有任何隐式的事情发生,并且你知道你在做什么:
The compiler is warning you not just you might get out of range, but that you might lose information (It needs to round up the number somehow, and is afraid to do it by its own).
Use
floor()
to tell it you know what you're doing:Or you could cast explicitly just to tell the compiler that there's nothing implicit going on, and you know what you're doing: