开发者

Casting from double to int - Warning in Visual C++/CLI

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 开发者_如何学JAVAto be a value from 1 to 10, so I know that it will be okay. Can I eliminate this warning somehow?


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:

int newValue = floor(control->Value); 

Or you could cast explicitly just to tell the compiler that there's nothing implicit going on, and you know what you're doing:

int newValue = (int)(float)(control->Value); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜