我在 C# (Unity) 中将 float 转换为 int 时遇到一些问题
当我尝试的时候 x * 1.05,得出x * 1 x * 1.1,结果是x * 1.05
using System;
public class Example
{
public static void Main()
{
int gainAmount = 20;
float _gainAmountModifier = 1.05f
gainAmount = (int)(gainAmount * _gainAmountModifier);
Debug.Log(_gainAmountModifier);
Debug.Log(gainAmount);
}
}
// The example displays output like the following:
// 1.05
// 20
当我在 C# 沙箱中测试它时
using System;
public class Example
{
public static void Main()
{
int var_int = 100;
float var_f = var_int;
var_f = var_f * 1.05f;
var_int = (int)var_f;
Console.WriteLine(var_f);
Console.Write(var_int);
}
}
// The example displays output like the following:
// 105
// 104
所以看起来像是向下舍入 1?
浮点数并不精确!
1.05
也可以是 1.049999999
或 1.050000001
(或类似)。
不要强制转换
(int)
,它总是简单地截取小数,只需使用 Mathf.RoundToInt
,这也会产生 105
,而不需要更重的数据类型(如 double
或 decimal
)