gpt4 book ai didi

c# - unity c# Mathf.FloorToInt(-0.5) 返回 0 (作用类似于 Mathf.CielToInt)

转载 作者:行者123 更新时间:2023-12-03 09:16:51 26 4
gpt4 key购买 nike

这是 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;
}

这是有效的版本(在 statRoll = 9 的情况下返回 -1):

    public int getBonus(int statRoll)
{
float initial = statRoll - 10;
float divided = initial / 2;
int result = Mathf.FloorToInt(divided);
return result;
}

最佳答案

您正在通过整数除法得到位。 statRoll10 都是 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;
}

当您执行-1/2时,您有两个整数,其计算结果为0而不是-0.5,因为结果也必须是国际。解决此问题的方法是将两个值之一设为 float

public int getBonus(int statRoll)
{
int result = Mathf.FloorToInt((statRoll - 10) / 2f); //adding f after a number makes it a float
return result;
}

这使得 int 和 float 之间的除法得到 float 。类似的代码是

public int getBonus(int statRoll)
{
int initial = statRoll - 10;
float devisor = 2f;
float divided = initial / devisor ;
int result = Mathf.FloorToInt(divided);
return result;
}

关于c# - unity c# Mathf.FloorToInt(-0.5) 返回 0 (作用类似于 Mathf.CielToInt),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36510801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com