The*_*tor 2 c# floor unity-game-engine math-functions
这是Mathf.FloorToInt的脚本参考文档正如您所看到的,它应该将 -0.5 舍入到 -1。由于某种原因,当与我的计算一起使用时,它似乎将其返回为 0。
我有相同函数的两个版本,它们的工作方式非常相似,但输出不同。我的代码只会向这些函数提交 3 到 18 之间的整数。
此版本的行为就像使用 Mathf.CielToInt (在 statRoll = 9 的情况下返回 0):
public int getBonus(int statRoll)
{
int result = Mathf.FloorToInt((statRoll - 10) / 2);
return result;
}
Run Code Online (Sandbox Code Playgroud)
这是有效的版本(在 statRoll = 9 的情况下返回 -1):
public int getBonus(int statRoll)
{
float initial = statRoll - 10;
float divided = initial / 2;
int result = Mathf.FloorToInt(divided);
return result;
}
Run Code Online (Sandbox Code Playgroud)
您正在通过整数除法获得位。和statRoll都是10类型int,这initial实际上使得int.
你的第一个代码相当于
public int getBonus(int statRoll)
{
int initial = statRoll - 10;
int devisor = 2;
int divided = initial / devisor;
float castDevided = (float)divided
int result = Mathf.FloorToInt(castDevided);
return result;
}
Run Code Online (Sandbox Code Playgroud)
当你-1 / 2有两个 int 时,其计算结果为0not -0.5,因为结果也必须是 int。解决这个问题的方法是将两个值之一设为float
public int getBonus(int statRoll)
{
int result = Mathf.FloorToInt((statRoll - 10) / 2f); //adding f after a number makes it a float
return result;
}
Run Code Online (Sandbox Code Playgroud)
int这使得 a和 a之间的除法float产生浮点数。类似的代码是
public int getBonus(int statRoll)
{
int initial = statRoll - 10;
float devisor = 2f;
float divided = initial / devisor ;
int result = Mathf.FloorToInt(divided);
return result;
}
Run Code Online (Sandbox Code Playgroud)