从float到int的类型转换错误

时间:2015-01-10 12:00:17

标签: visual-studio c#-4.0

我使用以下代码从float到int进行类型转换。我总是浮动最多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。

3 个答案:

答案 0 :(得分:0)

这完全是因为漂浮和精密双重和四舍五入到整数

默认情况下,算术运算以双精度执行

这是您的第一个代码

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?

答案 1 :(得分:0)

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

答案 2 :(得分:-3)

使用此:

float temp1 = 25.3;
int temp = Int32. conversation (temp1)
相关问题