【问题标题】:typecast from float to int error从 float 到 int 的类型转换错误
【发布时间】:2015-01-10 12:00:16
【问题描述】:

我正在使用以下代码从浮点类型转换为整数。我总是有最多 1 个小数点的浮点数。首先我将它乘以 10,然后将其类型转换为 int

float temp1 = float.Parse(textBox.Text);
int temp = (int)(temp1*10);

对于 25.3,我在类型转换后得到 252,但对于 25.2、25.4,我分别得到正确的输出 252,254。

现在以不同的方式执行相同的操作会得到正确的输出。

float temp1 = float.Parse(textBox.Text);
temp1 = temp1*10;
int temp = (int)temp1;

现在 25.3 我得到 253。这是什么原因,因为逻辑上第一种方法也是正确的?我正在使用 Visual Studio 2010。

【问题讨论】:

  • 你确定不是float temp1 = 25.3?那不会编译。
  • 25.3 不能用二进制精确表示,所以四舍五入到最接近的数字,可能会少一点。转换为 int 只会截断基数分隔符后面的数字。
  • 此外,x86 会发生这种情况,但 x64 不会发生这种情况,这就解释了为什么将它放在变量中很重要。 x86 JIT 使用 FPU 指令,它比变量的类型更精确,因此您存储它的事实会改变值。
  • 对不起我的错误实际上我是从 c# 表单中读取 temp1 所以它是 float.Parse(textBox.Text)
  • (int) cast 截断浮点值。所以 252.99999(实际值)被截断为 25.2 你必须四舍五入,int temp = (int)(temp1*10 + 0.5);

标签: visual-studio c#-4.0


【解决方案1】:

这都是因为浮点和双精度以及四舍五入到整数

算术运算默认以双精度执行

这是你的第一个代码

float temp1 = float.Parse(textBox.Text);
int temp = (int)(temp1*10);

被执行为

float temp1 = float.Parse(textBox.Text);
double xVariable = temp1*10
int temp = (int)xVariable;

这是您的第二个代码,它作为乘法的浮点转换执行

float temp1 = float.Parse(textBox.Text);
float xVariable = temp1*10;
int temp = (int)xVariable;

关于精度的更多信息

http://en.wikipedia.org/wiki/Single-precision_floating-point_format

What range of numbers can be represented in a 16-, 32- and 64-bit IEEE-754 systems?

【讨论】:

    【解决方案2】:

    试试

    decimal temp1 = decimal.Parse(textBox.Text);
    int temp = (int)(temp1*10);
    

    【讨论】:

      【解决方案3】:

      使用这个:

      float temp1 = 25.3;
      int temp = Int32. conversation (temp1)
      

      【讨论】:

      • 那不仅不会编译,而且不会乘以 10...
      • 我在问第一步中某些值的错误答案的原因是什么,但在第二步中不是这样。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      相关资源
      最近更新 更多