简体   繁体   English

设置为浮点数时,NumericUpDown值变为0

[英]NumericUpDown Value turns to 0 when it is set as a float

So resizeWidth and resizeHeight are numericUpDown controls in this following code. 因此,在以下代码中,resizeWidth和resizeHeight是numericUpDown控件。 Also, tempBitmapW and tempBitmapH are both floats. 同样,tempBitmapW和tempBitmapH都是浮点数。

float rW = (float)resizeWidth.Value;
float rH = (float)resizeHeight.Value;
rH = (float)Math.Truncate(tempBitmapH * ((float)rW / tempBitmapW));
int rsW = (int)rW;
int rsH = (int)rH;
resizeWidth.Value = rsW;
resizeHeight.Value = rsH;

Now when I debug this, rsW and rsH and rW and rH do not read as 0, none of them. 现在,当我调试此命令时,rsW和rsH以及rW和rH都不读为0,它们都不是。 But for some reason the numericUpDown controls throw an error as the Value 0 is out side the Minimum/Maximum range (the minimum is set to 1), so basically it is reading it as 0. 但是由于某种原因,由于值0在最小/最大范围之外(最小值设置为1),因此numericUpDown控件会引发错误,因此基本上将其读取为0。

What have I done wrong? 我做错了什么?

You just dont understand correctly how casts work. 您只是不正确理解强制转换的工作方式。 Because of the way you are casting floats to int, you are getting 0. The float value might be 0.42 but that will cast to 0 in an integer. 由于您将float转换为int的方式,您将获得0。float值可能是0.42,但它将整数转换为0。

You should check how casts work in detail, that will probably solve your problem. 您应该检查演员表的详细工作方式,这可能会解决您的问题。

To expand on squelos' answer- it sounds like perhaps the moment when you're looking at the values in the debugger and the moment when the exception is being thrown are two different moments in time. 为了扩展squelos的答案-听起来好像您在调试器中查看值的时刻与引发异常的时刻是两个不同的时刻。 If you're getting an exception saying the value is zero- it's probably because the value is zero. 如果您收到一个异常,说该值是零,则可能是因为该值是零。

The reason it might become zero is because the cast from float to int always rounds down to the nearest integer. 之所以可能为零的原因是,从float到int的转换总是四舍五入到最接近的整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM