VB.NET Code:
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
C# Code:
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
I don't get it, would appreciate an explanation.
C# /
performs integer division, truncating the fractional portion. VB.NET implicitly casts to 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
. Any int/int
(int divided by int) results in integer division, which discards any fractional remainder, losing precision. 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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With