[英]Why is this code returning different values? ( C# and VB.NET )
VB.NET Code: VB.NET代码:
Module Module1
Sub Main()
Dim x, y As Single
x = 0 + (512 / 2 - 407) / 256 * 192 * -1
y = 0 + (512 / 2 - 474) / 256 * 192
Console.WriteLine(x.ToString + ": " + y.ToString)
Console.ReadLine()
End Sub
End Module
Returns: 113,25: -163,5 返回:113,25:-163,5
C# Code: C#代码:
class Program
{
static void Main(string[] args)
{
float x, y;
x = 0 + (512 / 2 - 407) / 256 * 192 * -1;
y = 0 + (512 / 2 - 474) / 256 * 192;
Console.WriteLine(x + ": " + y);
Console.ReadLine();
}
}
returns 0: 0 返回0:0
I don't get it, would appreciate an explanation. 我不明白,会很感激解释。
C# /
performs integer division, truncating the fractional portion. C# /
执行整数除法,截断小数部分。 VB.NET implicitly casts to Double
. VB.NET隐式转换为Double
。
To perform floating point division, cast to a floating point type: 要执行浮点除法,请转换为浮点类型:
static void Main(string[] args)
{
float x, y;
x = 0 + (512 / 2 - 407) / (float)256 * 192 * -1;
y = 0 + (512 / 2 - 474) / (float)256 * 192;
Console.WriteLine(x + ": " + y);
Console.ReadLine();
}
C# literals like 0
and 512
are of type int
. 像0
和512
这样的C#文字是int
类型。 Any int/int
(int divided by int) results in integer division, which discards any fractional remainder, losing precision. 任何int/int
(int除以int)都会产生整数除法,它会丢弃任何小数余数,从而失去精度。 If you use float literals like 0F
instead of 0
and 512F
instead of 512
, then C# will perform floating point division, which will retain the fractional part. 如果使用浮点文字,如0F
而不是0
和512F
而不是512
,则C#将执行浮点除法,这将保留小数部分。
static void Main(string[] args)
{
float x, y;
x = 0F + (512F / 2F - 407F) / 256F * 192F * -1F;
y = 0F + (512F / 2F - 474F) / 256F * 192F;
Console.WriteLine(x + ": " + y);
Console.ReadLine();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.