除以两个数字总是等于零?

在我的Xna游戏中,我试图让我的playfield缩放到它正在运行的屏幕上。 为此,我使用比例来查找真实窗口相对于我的playfield缩放的百分比。 为此,我将实际宽度除以虚拟宽度:

float _percent = _realViewport.Width / this._viewport.Width; 

不过,我总是在_percent变量中得到0。 我在代码中的那一行设置了一个调试停止点,并分析了变量。 this._viewport.Width等于640,而_realViewport.Width等于1280.所以,使用我的计算器,640/1280应该等于0.5,但在我的代码中我总是得到0,而不是0.5。 它为什么这样做?

因为整数除法截断( XNA的Viewport类型具有整数宽度和高度属性),640/1280是0.5,它截断为零。

如果您想要浮点除法,请将您的一个值转换为浮点数:

 float _percent = _realViewport.Width / (float)this._viewport.Width; 

试试这个float _percent = _realViewport.Width * 1.0/ (float)this._viewport.Width; ,通过添加乘以1.0,整数将自动转换为float。